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);
}
}
Tại sao in "Derived.foo:" 10, nulll
chứ không phải 20 thay vì null? y là biến riêng của Derived, và nó đã được khởi tạo với 20. nó nằm trong phạm vi của nó .. vậy tại sao nó rỗng?Java- tại sao nó in null?
+1. Vâng giải thích. – Mikaveli
+1, đặc biệt là cảnh báo thực hành xấu: _it có thể gọi các phương thức ghi đè trên đối tượng được tạo một phần_. –