簡體   English   中英

從抽象類Java繼承后的Access屬性

[英]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修飾符,如果需要操縱基類並訪問特定於子類的某些字段,則可以在基類中定義一個返回nullOptional ,在子類中使用字段的返回值覆蓋它。
它避免了可能容易出錯且通常是概念問題症狀的轉換。

您的實例是AplicationC,
因此,“ instance.student”是“ Student”。
“學生”沒有“ currentSchool”屬性。
去實現它
*將“ currentSchool”屬性添加到“學生”
要么
*將您的“ instance.student”轉換為“ ExternalStudent”

注意:您將需要處理所有例外情況和轉換費用等。

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM