我正在尝试创建一个父类(super class),用于存储存储常用方法的 InPatient 类和 OutPatient 类的详细信息。我已经成功地毫无问题地转移到了身份领域,但在转移药物方面却遇到了困难。改变时的setMedicate方法上
this.medication = medication;
至
this.getMedication() = medication;
我被告知我应该插入一个变量而不是一个值,但无法弄清楚我应该在它的位置放入什么变量。
我有 InPatient 类(class):
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;
}
}
它是父类(super class) Patient:
/**
* 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;
}
}
我在这里缺少什么?
最佳答案
不能将函数调用放在赋值的左侧。这根本没有道理。
如果medication
不是private
,您可以将您的方法分配给它。因为它是私有(private)
,所以你不能。解决办法有两种:
将
Patient
类中的private
更改为protected
。这使得子类可以直接访问它,而外部客户端仍然看不到medication
字段。(我的首选方法)向父级 (
Patient
) 添加一个setMedicate
方法。您可以将此protected
,以便子类可以调用setMedicate
,而外部客户端则不能。无论如何,InPatient
类将使用该方法来设置medication
(使用语法super.setMedicate(medication)
,以便它调用父类中的方法)。
关于java - 将访问器和修改器方法从一个类移至其父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20984401/