public class Base {
public Base() {
x = 0;
bar();
}
public Base(int x) {
this.x = x;
foo();
}
public void foo() {
System.out.println("Base.foo : " + x);
}
private void bar() {
System.out.println("Base.bar:" + x.toString());
}
protected Integer x;
}
public class Derived extends Base {
public Derived() {
bar();
}
public Derived(int x, int y) {
super(x);
this.y = y;
}
public void foo() {
System.out.println("Derived.foo : " + x + ", " + y);
}
public void bar() {
System.out.println("Derived.bar:" + x.toString() + ", " + y.toString());
}
private Integer y;
public static void main(String[] args) {
Base b = new Derived(10, 20);
}
}
爲什麼它打印"Derived.foo:" 10, nulll
而不是20而不是空? y是一個Derived的私有變量,它的初始值是20.它在它的範圍內..所以爲什麼它是空的?Java-爲什麼它打印出null?
+1。很好解釋。 – Mikaveli
+1,特別是對於不良練習警告:_it可以在部分構建的objects_上調用重寫的方法。 –