static声明的变量和方法:静态变量和静态方法
静态变量和静态方法生命周期和类相同,它有如下特点:
- 为该类的公用变量,属于类,被该类所有实例共享,在类被载入时被初始化
- static变量只有一份
- 一般用"类名.类变量/方法"调用
- 在类变量中不可以直接访问非static成员
public class TestStatic {
int id;
String name;
String pwd;
static String company = "123有限公司";
public TestStatic(int id, String name) {
this.id = id;
this.name = name;
}
public void login() {
System.out.println(this.name);
}
public static void printCompany() {
// login() 无法调用非静态方法,会编译报错
System.out.println(company);
}
public static void main(String[] args) {
TestStatic u = new TestStatic(101, "张三");
TestStatic.printCompany();
TestStatic.company = "456有限公司";
TestStatic.printCompany();
u.login();
}
}