我無法訪問繼承自抽象類的具體類型的類的字段。從抽象類繼承後訪問屬性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
}
但我無法訪問學生實例的當前學校(他必須是外部學生)。我如何訪問此字段以測試我的代碼?
行政長官,是的向下轉換對我來說是有意義的。我認爲這樣做沒有缺點? – stevenpcurtis
它有一些。我正在編輯解釋:) – davidxxx
謝謝,感謝。 – stevenpcurtis