java - 从Java抽象类继承后访问属性

标签 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;
    }
}

外部学生是由我的类(class)应用程序设置的

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
}

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

最佳答案

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 的基类中,并在子类中使用字段的返回值覆盖它。
它避免了可能容易出错并且通常是受孕问题症状的铸型。

关于java - 从Java抽象类继承后访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993689/

相关文章:

java - 空指针异常

java - 访问子类对象自己的私有(private)字段

ios - Swift:继承 ViewController 并添加目标?

java - 带有 Java API 的 Node Web 应用程序

java - 如何删除 Linux 上 IntelliJ 下载的旧 Gradle 文件和 JDK?

java - 使用FileReader时如何写入文件路径?

c++ - 为什么我必须通过 this 指针访问模板基类成员?

JavaScript 原型(prototype)构造函数仅调用一次

c++ - 语言环境构面构造函数被忽略

java - Selenium:让 findElements 等待可见元素,尽管存在不可见元素