2017-07-09 37 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