日期:2014-05-20 浏览次数:20752 次
package zhao; public class Test2 extends AA { static int age = 20;// 3 String code = "ANA";//8 static { System.out.println("Test2 class static--------" + age);// 4 } { System.out.println("Test2 class not static--------" + code);//9 } Test2() { code = "DHC"; System.out.println("Test2()--------" + age);//10 } public static void main(String[] args) { try { Class.forName("zhao.Test2"); } catch (ClassNotFoundException e) { e.printStackTrace(); } new Test2(); } } class AA { static String tel = "123"; // 1 String name = "zhao";// 5 static { System.out.println("AA class static--------" + tel);// 2 } { System.out.println("AA class not static--------" + name);//6 } AA() { name = "kimi"; System.out.println("AA()--------" + tel);//7 } }
------解决方案--------------------
class Cup { Cup(int marker) { System.out.println("Cup (" + marker + " )"); } void f(int marker) { System.out.println("f( " + marker + " )"); } }; class Cups { static Cup cup1; static Cup cup2; static //静态子句,或者说是"静态块" { cup1 = new Cup(1); cup2 = new Cup(2); } Cups() { System.out.println("Cups"); } }; public class P97 { public static void main(String[] args) { Cups.cup1.f(3); //访问静态cup1对象. new Cups(); } //static Cups cups1 = new Cups(); //static Cups cups2 = new Cups(); }; /*output Cup (1 ) Cup (2 ) f( 3 ) Cups */
------解决方案--------------------
public class Father { String fs = "Father's attribute"; { System.out.println(fs); } static String fss = "Father's static attribute"; static{ System.out.println(fss); } Father(){ System.out.println("Father's constructor"); } } class Child extends Father{ String cs = "Child's attribute"; { System.out.println(cs); } static String css = "Child's static attribute"; static{ System.out.println(css); } Child(){ System.out.println("Child's constructor"); } } class Test{ public static void main(String[] args) { Child c = new Child(); } } /* 这里是运行结果: Father's static attribute Child's static attribute Father's attribute Father's constructor Child's attribute Child's constructor */