我正在尝试创建一个超类,它存储了存储常用方法的类InPatient和OutPatient的详细信息。我已经设法在没有任何问题的情况下移动到id字段,但是当涉及到移动药物时我正在努力。改变时使用setMedication方法
this.medication = medication;
到
this.getMedication() = medication;
我被告知我应该插入一个变量而不是一个值,但是无法弄清楚我应该把它放在哪个变量中。
我有InPatient课程:
public class InPatient extends Patient
{
// The condition of the patient.
private String status;
// Whether the patient is cured or not.
private boolean cured;
public InPatient(String base, String id)
{
status = base;
cured = true;
}
/**
* Set the patient's medication
* The patient is no longer cured
*/
public void book(String medication)
{
setMedication(medication);
cured = false;
}
/**
* Show the patients details.
*/
public String getDetails()
{
return getID() + " at " + status + " headed for " +
getMedication();
}
/**
* Patient's status.
*/
public String getStatus()
{
return status;
}
/**
* Set the patient's medication.
*/
public void setMedication(String medication)
{
this.getMedication() = medication;
}
/**
* Show that the patient is cured
*/
public void better()
{
status = medication;
medication = null;
cured = true;
}
}
它是超级病人:
/**
* Write a description of class Patient here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Patient
{
// Patient's ID.
private String id;
// Medication the patient is on.
private String medication;
/**
* Constructor for objects of class Patient
*/
public Patient()
{
this.id = id;
medication = null;
}
/**
* The patient's ID.
*/
public String getID()
{
return id;
}
/**
* Patient's medication
*/
public String getMedication()
{
return medication;
}
}
我在这里缺少什么?
答案 0 :(得分:0)
基础/父级:
class Patient {
private String medication;
public String getMedication() { return this.medication; }
public String setMedication(String __medication) {
this.medication = __medication;
}
}
儿童/扩展班级:
class InPatient extends Patient {
public String getMedication() { super.getMedication(); }
public String setMedication(String __medication) {
super.setMedication(String __medication);
}
// if medication is being instantiated using the value from parent class
public String setMedication() {
this.medication = super.getMedication();
}
}
答案 1 :(得分:0)
您不能在作业的左侧放置函数调用。这没有意义。
如果medication
不是private
,您可以将方法分配给它。由于它是private
,你不能。有两种解决方案:
在private
课程中将protected
更改为Patient
。这允许子类直接访问它,而外部客户端仍然看不到medication
字段。
(我的首选方法)向父(setMedication
)添加Patient
方法。您可以创建此protected
,以便子类可以调用setMedication
,而外部客户则不能。无论如何,InPatient
类将使用该方法设置medication
(使用语法super.setMedication(medication)
,以便它调用父类中的方法)。