如何在 Java 中的对象之间传递消息

问题描述

我试图在具有 OOP 概念的 Java 对象之间传递消息。我创建了两个名为 Doctor 和 Receptionist 的类,我希望 Receptionist 类的实例向 Doctor 的对象发送消息。我还希望 Patient 类的对象向 Appointments 类的对象发送消息(预约约会)。

总而言之,我想实现不同类的不同实例之间的关系和通信。

患者分类

public class Patient 
{
    private int id;
    private String name;
    private int age;
    private String condition;

    public Patient (int id,String name,int age,String condition)
    {
        this.setId(id);
        this.setName("name");
        this.setAge(age);
        this.setCondition("condition");
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public int getId()
    {
        return this.id;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getAge()
    {
        return this.age;
    }
    public void setCondition(String condition)
    {
        this.condition = condition;
    }
    public String getCondition()
    {
        return this.condition;
    }
}

预约班

public class Appointment {
    private int appointId;
    private String date;
    private String purpose;
    
    public Appointment (int appointId,String date,String purpose)
    {
        this.setAppointId(appointId);
        this.setDate("date");
        this.setPurpose("purpose");
    }
    public void setAppointId(int appointId)
    {
        this.appointId = appointId;
    }
    public void setDate(String date)
    {
        this.date = date;
    }
    public void setPurpose(String purpose)
    {
        this.purpose = purpose;
    }
}

怎样才能有一个方法在Patient类中预约;并且当该方法调用时,它会创建一个 Appointment 的实例?

解决方法

您的 Patient 类可能如下所示:

public class Patient {
    private int id;
    private String name;
    private int age;
    private String condition;

    public Patient( int id,String name,int age,String condition ) {
        this.setId(id);
        this.setName("name");
        this.setAge(age);
        this.setCondition("condition");
    }

    public void setId( int id ) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public void setName( String name ) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setAge( int age ) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }

    public void setCondition( String condition ) {
        this.condition = condition;
    }

    public String getCondition() {
        return this.condition;
    }

    public Appointment bookAnAppointment( int appointId,String date,String purpose ) {
        return new Appointment(appointId,date,purpose);
    }
}