在此代碼中,我只分配一個對象,但在某些方面,我存儲了2個x副本(一個用於基類,另一個用於子類)。如果對象只有一個,它怎麼可能?發現存儲兩個x變量的空間在哪裏?這是否意味着實際上創建了兩個對象?存儲兩個具有相同名稱的變量的對象
class App {
class Base {
public int x;
public Base() {
x = 2;
}
int method() {
return x;
}
}
class Subclass extends Base {
public int x;
public Subclass() {
x = 3;
}
int method() {
return x;
}
}
public static void main(String[] args) {
new App().run();
}
public void run() {
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.method());
}
}