static 静态变量和静态方法
/**
* 测试static 静态变量和静态方法 随类加载到方法区内
* 静态初始化块
*/
public class TestStatic {
int id;
String name;
static String country = "China";
//static变量 静态变量属于类 不属于对象 new的对象不具有country属性
public TestStatic(int id, String name) {
this.id = id;
this.name = name;
//右键generate constructor 生成构造方法
}
void aaa(){}
public static void where(){
//void 无返回值
System.out.println(country);
//static方法内可以调用static变量或static方法
//static方法属于类,类方法调用类对象不用再定义country直接使用
//普通方法aaa属于对象,类方法无法调用
//this属于对象,类方法也无法调用
}
public static void main(String[] args) {
TestStatic u1 = new TestStatic(01,"li");
TestStatic.where();
//调用static方法即类方法,输入类名.方法名()
u1.aaa();
//u1指向对象调用aaa方法,对象.方法名()
TestStatic.country = "CN";
//静态变量可修改
TestStatic.where();
}
}
class TestStatic2{
static String country;
static {
//语句块外加static 静态初始化块 在类加载时执行
System.out.println("类的初始化操作执行中");
country = "China";
//调用类变量country
where();
//调用类方法where
}
public static void where(){
System.out.println(country);
}
public static void main(String[] args) {
//main方法空
}
}