gpt4 book ai didi

java - 在 Java 中声明嵌套类

转载 作者:行者123 更新时间:2023-12-04 21:28:27 24 4
gpt4 key购买 nike

我对子类有点困惑。这是我的代码:

public class MedHistory {

private String grafts;
private String allergies;
private String diseases;
private String surgeries;
private String medicalTreatment;

//Constructors (#2)

public MedHistory(String allergies, String diseases, String grafts,
String treatments, String surgeries) {
this.allergies=allergies;
this.diseases=diseases;
this.grafts=grafts;
this.medicalTreatment=treatments;
this.surgeries=surgeries;
}

public MedHistory() {
this.allergies="";
this.diseases="";
this.grafts="";
this.medicalTreatment="";
this.surgeries="";
}

//Getters
public String getGrafts() {
return grafts;
}

public String getAllergies() {
return allergies;
}

public String getDiseases() {
return diseases;
}

public String getSurgeries() {
return surgeries;
}

public String getMedicalTreatment() {
return medicalTreatment;
}

//Setters

public void setGrafts(String grafts) {
this.grafts = grafts;
}

public void setAllergies(String allergies) {
this.allergies = allergies;
}

public void setDiseases(String diseases) {
this.diseases = diseases;
}

public void setSurgeries(String surgeries) {
this.surgeries = surgeries;
}

public void setMedicalTreatment(String medicalTreatment) {
this.medicalTreatment = medicalTreatment;
}

public class FemMedHistory extends MedHistory {

private List<Birth> births = new ArrayList<Birth>();

//Constructors (#2)

public FemMedHistory(String allergies, String diseases, String grafts,String treatments, String surgeries, List<Birth> birthlist) {
super(allergies,allergies,grafts,treatments,surgeries);
this.births=birthlist;
}

public FemMedHistory() {
super();
this.births=null;
}

//Getter

public List<Birth> getBirths() {
return this.births;

}

//Setter

public void setBirths(List<Birth> list) {
this.births=list;
}

}
}

当我尝试像这样创建一个新的 FemMedHistory 对象时:

List<Birth> list = new ArrayList<Birth>();
list.add(new Birth(new GregorianCalendar(2011,4,10),"kaisariki",4));
FemMedHistory female = new FemMedHistory("allergia2","astheneia2","emvolia2","farmekeutiki agwgi2", "xeirourgeia2", list);

我得到错误:

No enclosing instance of type MedHistory is accessible. Must qualify the allocation with an enclosing instance of type MedHistory (e.g. x.new A() where x is an instance of MedHistory).

那么,子类的正确使用方法是什么?

最佳答案

当您声明一个嵌套类时,它只能通过外部类使用。

要在外部访问它,您需要将 FemMedHistory 类设为静态。

public static class FemMedHistory extends MedHistory {...}

通过 MedHistory 类访问它

MedHistory.FemMedHistory myMedHistory = ...

或者在它自己的 Java 文件中声明它。

关于java - 在 Java 中声明嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com