基本规则
Java中static关键字修饰的成员变量和方法是静态变量和方法,使用规则如下:
1. static方法只能调用static方法或static变量,不能调用非static方法或非static变量,换句话说就是,静态方法只能调用静态方法或静态变量,不能调用非静态方法或非静态变量。注:在静态方法中可以通过创建对象,通过创建的对象调用该对象的非静态方法。
2.static方法中不能使用this或super关键字。
3.static不能用于修饰局部变量,另外构造器不是静态方法,因为构造器里可以引用this和super关键字。
初始化时间
静态变量和静态代码块在类初次加载时会被初始化,且只能被初始化一次。(静态代码块不能写在方法体里面)
注:当子类没有与其父类同名的static变量或方法时,子类也能调用父类的static变量或方法,但是子类并没有继承父类中static修饰的变量和方法。因为static修饰的变量和方法是属于父类本身的。
例如:
public class StaticTest {//父类
public static String superStr = "father==";//静态变量
public static String getSuperStr() {//静态方法
String superS = "invoke Super static method...";
return superS;
}
}
public class ChildStaticTest extends StaticTest{//子类
//子类中没有与父类同名的static变量和static方法
}
public class MainTest {//测试类
public static void main(String[] args) {
System.out.println(ChildStaticTest.superStr);
System.out.println(ChildStaticTest.getSuperStr());
ChildStaticTest cst = new ChildStaticTest();
System.out.println(cst.superStr);
System.out.println(cst.getSuperStr());
}
}
输出结果是:
father==
invoke Super static method...
father==
invoke Super static method...
假如子类中存在与父类同名的static变量和static方法
public class ChildStaticTest extends StaticTest{
public static String superStr = "child==";
public static String getSuperStr() {
String childS = "invoke child static method...";
return childS;
}
}
输出结果是:
child==
invoke child static method...
child==
invoke child static method...