package day01; class Base{ int j; //1.j=0 Base(){ add(1); //2.调用子类add()方法 System.out.println(j); //4,父类j=0,打印0 } public void add(int i) { j=j+1; } } class MyBase extends Base{ int j=5; //5,j=5 MyBase(){ System.out.println(j); //打印5 } public void add(int i) { j=j+i+1; System.out.println(j); //3, 此时子类j还没显示初始化,默认值0,j=2,打印2 } } public class Tester { public static void main(String[] args) { new MyBase(); } }
2
0
5
但是当稍微改变下时,
package day01; class Base{ public int j; //1.j=0 Base(){ add(1); //2.调用子类add()方法 System.out.println(j); //4,这里为什么打印2,不该是0吗?why? } public void add(int i) { j=j+1; } } class MyBase extends Base{ MyBase(){ System.out.println(j); } public void add(int i) { j=j+i+1; System.out.println(j); //3, 此时子类j还没显示初始化,默认值0,j=2,打印2 } } public class Tester { public static void main(String[] args) { new MyBase(); } } /* 2 * 2 * 2 */