publicclass TStatic { staticinti; public TStatic() { i = 4; } public TStatic(int j) { i = j; } publicstaticvoid main(String args[]) { System.out.println(TStatic.i); TStatic t = new TStatic(5);// 声明对象引用,并实例化。此时i=5 System.out.println(t.i); TStatic tt = new TStatic();// 声明对象引用,并实例化。此时i=4 System.out.println(t.i); System.out.println(tt.i); System.out.println(t.i); }} |
class ClassA { intb; publicvoid ex1() {} class ClassB { void ex2() { int i; ClassA a = new ClassA(); i = a.b;// 这里通过对象引用访问成员变量b a.ex1(); // 这里通过对象引用访问成员函数ex1 } }} |
class ClassA { staticintb; staticvoid ex1() {}} class ClassB { void ex2() { int i; i = ClassA.b;// 这里通过类名访问成员变量b ClassA.ex1(); // 这里通过类名访问成员函数ex1 }} |
publicclass StaticCls { publicstaticvoid main(String[] args) { OuterCls.InnerCls oi = new OuterCls.InnerCls();//这之前不需要new一个OuterCls }} class OuterCls { publicstaticclass InnerCls { InnerCls() { System.out.println("InnerCls"); } }} |
class Value { staticintc = 0; Value() { c = 15; } Value(int i) { c = i; } staticvoid inc() { c++; }} class Count { publicstaticvoid prt(String s) { System.out.println(s); } Value v = new Value(10); static Valuev1, v2; static { prt("in the static block of calss Count v1.c=" +v1.c +" v2.c=" + v2.c); v1 =new Value(27); prt("in the static block of calss Count v1.c=" +v1.c +" v2.c=" + v2.c); v2 =new Value(); prt("in the static block of calss Count v1.c=" +v1.c +" v2.c=" + v2.c); }} publicclass TStaticBlock { publicstaticvoid main(String[] args) { Count ct = new Count(); Count.prt("in the main:"); Count.prt("ct.c=" + ct.v.c); Count.prt("v1.c=" + Count.v1.c + " v2.c=" + Count.v2.c); Count.v1.inc(); Count.prt("v1.c=" + Count.v1.c + " v2.c=" + Count.v2.c); Count.prt("ct.c=" + ct.v.c); }} |