类 变量 就是 static 修饰 的 变量, 它们 被 类 的 实例 所 共享, 就是说 一个 实例 改变 了 这个 值, 其他 的 实例 也会 受到影响; 成员 变量 则是 实例 所 私有 的, 只有 实例 本身 可以 改变 它的 值。
/**
* Created by xabcd on 2019/2/14.
*/
public class Test
{
static String a = "string-a";
static String b;
String c = "string-c";
String d;
static {//此处不能改成public xxx()也不能用static xxx()
printStatic("before static");
b = "string-b";
printStatic("after static");
}
public static void printStatic(String title){
System.out.println("--------"+title+"--------");
System.out.println("a = \""+a+"\"");
System.out.println("b= \""+b+"\"");
}
public Test(){//此处不能改成static
print("before constructor");
d = "string-d";
print("after contructor");
}
public void print(String title){
System.out.println("--------"+title+"--------");
System.out.println("a=\""+a+"\"");
System.out.println("b=\""+b+"\"");
System.out.println("c=\""+c+"\"");
System.out.println("d=\""+d+"\"");
}
public static void main(String[] args){
new Test();//一定要用new Test???
}
}
结果:
--------before static--------
a = "string-a"
b= "null"
--------after static--------
a = "string-a"
b= "string-b"
--------before constructor--------
a="string-a"
b="string-b"
c="string-c"
d="null"
--------after contructor--------
a="string-a"
b="string-b"
c="string-c"
d="string-d"
