[英]Access property after inheriting from an abstract class Java
我无法访问从抽象类继承来的具体类型的类的字段。
在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
}
但是我无法访问该学生实例的当前学校(该学生必须是一名外部学生)。 如何访问此字段以测试我的代码?
在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
修饰符,如果需要操纵基类并访问特定于子类的某些字段,则可以在基类中定义一个返回null
或Optional
,在子类中使用字段的返回值覆盖它。
它避免了可能容易出错且通常是概念问题症状的转换。
您的实例是AplicationC,
因此,“ instance.student”是“ Student”。
“学生”没有“ currentSchool”属性。
去实现它
*将“ currentSchool”属性添加到“学生”
要么
*将您的“ instance.student”转换为“ ExternalStudent”
注意:您将需要处理所有例外情况和转换费用等。
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.