继承自抽象类Java后的Access属性

时间:2017-07-09 06:35:48

标签: java inheritance

我无法访问继承自抽象类的具体类的类的字段。

在Java中,我创建了一个扩展Student

的外部学生
 */
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
}

但我无法访问学生实例的当前学校(必须是外部学生)。如何访问此字段以测试我的代码?

2 个答案:

答案 0 :(得分:1)

ApplicationC中,student字段与Student类一起声明:

Student student;

对象上可用的方法依赖于声明的类型,而不是真正实例化的对象 并且currentSchool仅在子类ExternalStudent中声明 所以,你不能以这种方式访问​​它。

解决方法是将Student向下转换为ExternalStudent

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

通常,最好在执行之前检查实例的类型:

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

作为一般建议,在Java中,您应该支持字段的private修饰符,如果您需要操作基类并访问特定于子类的某些字段,您可以在基础中定义方法返回nullOptional的类,并在子类中使用字段的返回覆盖它 它避免了可能容易出错并且通常是受孕问题的症状。

答案 1 :(得分:1)

您的实例是AplicationC,
所以,“instance.student”是“学生” “学生”没有“currentSchool”财产 到达它 *将“currentSchool”属性添加到“学生”中 或
*将您的“instance.student”投射到“ExternalStudent”

注意:您需要处理所有异常和投射等问题

希望这有帮助