public class Test { private String a ="d"; public Test(){ call(); //this.call(); } public void call(){ System.out.println("父类的构造方法别调用"+a); } static class Test1 extends Test{ private String a = "sdf"; public void call(){ System.out.println(a); } } public static void main(String[] args){ Test t = new Test1(); //null t.call(); //sdf } }
为null的原因在于,call()方法第一次调用的时候是在创建父类的时候调用的,此时a变量还没有被赋值,所以为null
public class Test { private String a ="d"; public Test(){ call(); //this.call(); } public void call(){ System.out.println("父类的构造方法别调用"+a); } static class Test1 extends Test{ private String a = "sdf"; // public void call(){ // System.out.println(a); // } } public static void main(String[] args){ Test t = new Test1(); //父类的构造方法别调用d t.call(); //父类的构造方法别调用d } }