2017-07-09 50 views
0

我無法訪問繼承自抽象類的具體類型的類的字段。從抽象類繼承後訪問屬性Java

在Java中,我創建一個類外的學生,擴展學生

*/ 
public class ExternalStudent extends Student { 
String currentSchool; 

    public ExternalStudent(String name, Integer age, String studentIdentifier, String currentSchool) { 
    super(name, age, studentIdentifier); 
    this.currentSchool = currentSchool; 
    } 
} 

其中學生

public abstract class Student { 

    //Attributes 
    String studentIdentifier; 
    Integer age; 
    String name; 

    //Associations 
    List<Subject> subject = new ArrayList<Subject>(); 
    PersonalDetails personaldetails; 

    //Methods 
    public void setSubject() { 
     this.subject.add(new Subject("Name")); 
    } 

    //Constructors 
    public Student(String name, Integer age, String studentIdentifier){ 
     this.age = age; 
     this.name = name; 
     this.studentIdentifier = studentIdentifier; 
    } 
} 

和外部的學生是通過我的類應用

public class ApplicationC { 
    //Attributes 
    private String personalStatement; 
    private String applicationForm; 

    //Associations 
    Registration registration; 
    Student student; 
    ApplicationTest applicationtest; 

    //Methods 
    public void setApplicationResult(String result){ 
     this.applicationtest = new ApplicationTest(result); 
    } 

    //Constructor 
    public ApplicationC (String personalStatement, String name){ 
     this.registration = new Registration(); 
     this.student = new ExternalStudent("Tom",16,"78954","DHS"); 
    } 
} 

成立我建立了一個簡單的測試課

public void testPostCondition() throws ParseException{ 
ApplicationC instance = new ApplicationC("test statement","test name"); 
    instance.setApplicationResult("pass");  
    assertEquals("pass",instance.applicationtest.result); 
     instance.student.age = 16; 
    instance.student.studentIdentifier = "78954"; 
    instance.student.name = "Tom"; 
    instance.student.currentSchool = "test"; //Error as field does not exist 
} 

但我無法訪問學生實例的當前學校(他必須是外部學生)。我如何訪問此字段以測試我的代碼?

回答

1

ApplicationC,該student字段聲明與Student類:可

Student student; 

方法上的對象依賴於聲明的類型,而不是真的實例化對象。
currentSchool僅在子類ExternalStudent中聲明。
所以,你不能以這種方式訪問​​它。

一種解決方法是向下轉換StudentExternalStudent

((ExternalStudent)instance.student).studentIdentifier = "78954"; 

而且一般,最好是做前檢查實例的類型:

if (instance.student instanceof ExternalStudent){ 
    ((ExternalStudent)instance.student).studentIdentifier = "78954"; 
} 

作爲一般的建議,在Java ,你應該支持字段的private修飾符,如果你需要操作基類並訪問特定於子類的某些字段,你可以在基類中定義一個返回的方法或Optional,並在字段返回的子類中覆蓋它。
它避免了可能容易出錯並且常常是受孕問題的症狀。

+0

行政長官,是的向下轉換對我來說是有意義的。我認爲這樣做沒有缺點? – stevenpcurtis

+1

它有一些。我正在編輯解釋:) – davidxxx

+0

謝謝,感謝。 – stevenpcurtis

1

你的實例是一個應用程序C,
所以,「instance.student」是一個「學生」。
「學生」沒有「currentSchool」屬性。
得到它
*添加「currentSchool」屬性設置爲「學生」

*投你「instance.student」到「ExternalStudent」

注意:您將需要處理所有的異常和鑄造等的頭頂'

希望這可以幫助

+0

一個很好的答案,缺乏上面的davidxxx的細節。 – stevenpcurtis