java - 将访问器和修改器方法从一个类移至其父类(super class)

标签 java inheritance superclass

我正在尝试创建一个父类(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),所以你不能。解决办法有两种:

  1. Patient 类中的 private 更改为 protected。这使得子类可以直接访问它,而外部客户端仍然看不到 medication 字段。

  2. (我的首选方法)向父级 (Patient) 添加一个 setMedicate 方法。您可以将此 protected ,以便子类可以调用setMedicate,而外部客户端则不能。无论如何,InPatient 类将使用该方法来设置medication(使用语法super.setMedicate(medication),以便它调用父类中的方法)。

关于java - 将访问器和修改器方法从一个类移至其父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20984401/

相关文章:

java - 从给定的 .txt 文件中提取整数

java - 当 netbeans 项目转换为可执行 jar 时,JLabel.setVisible 不起作用

c++ - 子类无法访问父类的变量

java - 如何在子组件中包含标准HST组件的所有参数?

c++ - 在 C++ 中通过子类访问父类(super class)的 protected 静态成员

javascript - 在 JavaScript 中调用重写的方法

java - Java线程生产者和使用者

java - 了解流操作的 Java 类型

Java - 对特定继承场景感到困惑

java - 我可以在我的父类(super class)中使用子类的名称吗?