2011-06-16 48 views
2

在下面的Java代碼奇怪的事情正在發生的人

public class Person { 
    int age = 18; 
} 

class Student extends Person { 
    public Student() { 
     this.age = 22; 
    } 

    public static void main(String[] args) { 
     Student student = new Student(); 
     student.doSomthing(); 
    } 

    void doSomthing() { 
     System.out.println(this.age); 
     System.out.println(super.age);// Here is something weird, at least for me till rightNow() 
    } 
} 

爲什麼super.age值是22,同樣的值作爲子類的年齡值,是不是應該是18 ;
任何幫助表示讚賞。
在此先感謝。

回答

7

年齡是超級類的領域。在子類的構造函數中,當你說this.age = 22時,你正在更新超類中的實例變量。

請嘗試以下...我沒有編譯器方便,但我認爲它可以做你所期望的。

public class Person { 
    int age = 18; 
} 

class Student extends Person { 

    int age; // Hides the super variable 

    public Student() { 
     this.age = 22; 
    } 

    public static void main(String[] args) { 
     Student student = new Student(); 
     student.doSomthing(); 
    } 

    void doSomthing() { 
     System.out.println(this.age); 
     System.out.println(super.age); 
    } 
} 
1

學生繼承年齡由父母,所以年齡和super.age沒有區別

1

沒有,正在發生的事情是正確的。當你創建一個子類(Student是Person的子類)時,該子類繼承了超類的所有字段(變量)。但是,只有一組變量:年齡只有一個值,即使它是繼承的。換句話說,當一個類繼承一個字段時,它不會創建一個新的副本 - 每個學生只有一個副本。

1

在這個源代碼中,thissuper是相同的實例變量,因爲您在超類中定義它,並且在子類中繼承它。

當你創建你的學生時,你將其初始化爲22,就是這樣。

0

你在你的Student類設置age,但父是一個聲明age和它們共享相同的變量 - 因此,它是有道理的值被修改。但是,Overriden方法會有所不同。

4

這是行爲像你所期望的。你還沒有宣佈學生的'年齡'成員,所以this.age自然會引用超類中定義的「年齡」。

下面的代碼將提供您期望的行爲(雖然像這樣的陰影變量通常是一個非常糟糕的主意)。

public static class Person { 
    int age = 18; 
} 

public static class Student extends Person { 
    int age = 18; 

    public Student() { 
     this.age = 22; 
    } 

    void doSomthing() { 
     System.out.println(this.age); 
     System.out.println(super.age); 
    } 
} 
1

沒什麼奇怪的,它的行爲是正確的。類Student沒有私有變量age,這會覆蓋父變量。

2

不,這是正確的。在構造函數中,你超越了超類的年齡。你可以做這樣的事情:

public class Person { 
    public int getAge() { 
     return 18; 
    } 
} 

class Student extends Person { 
    public Student() { 
    } 

    @Override 
    public int getAge() { 
     return 22; 
    } 

    public static void main(String[] args) { 
     Student student = new Student(); 
     student.doSomthing(); 
    } 

    void doSomthing() { 
     System.out.println(this.getAge()); //22 
     System.out.println(super.getAge()); //18 
    } 
}