被static修饰的方法为静态方法,之外的方法为实例方法。静态方法可直接使用类调用,实例方法必须创建实例后才能调用。java-doc
1. 示例
@Testvoid staticMethodTest(){//直接调用静态方法Boss.work();//创建实例Boss boss = new Boss();//调用实例方法boss.programming();}class Boss {String name;public void programming(){System.out.println("I am programming.");}public static void work(){System.out.println("I am working.");}}
执行结果
I am working.I am programming.
2. 区别
2.1 类外部调用
静态方法可直接使用类调用,实例方法必须创建实例后才能调用。
2.2 类内部调用
实例方法内可以调用静态方法,但是静态方法只能调用静态方法,不能调用实例方法。
//实例方法public void programming(){System.out.println("I am programming.");work(); // 静态方法}//静态方法public static void work(){System.out.println("I am working.");// 无法调用 programming() 实例方法}
2.3 使用synchronized修饰
被synchronized修饰时,若为静态方法,monitor则与该静态方法的所属类的Class对象相关联;若为实例方法,monitor则与调用该方法的实例对象关联。
官方示例
class Test {int count;synchronized void bump() {count++;}static int classCount;static synchronized void classBump() {classCount++;}}// 效果与下面一致class BumpTest {int count;void bump() {synchronized (this) { count++; }}static int classCount;static void classBump() {try {synchronized (Class.forName("BumpTest")) {classCount++;}} catch (ClassNotFoundException e) {}}}