声明Patient类表示在门诊室中的病人,此类对象也应包括:name(a string)、sex(a char)、age(an integer)、weight(a float)、allergies(a boolean)等属性,以及属性对应的getter/setter方法。在一个单独的类中,声明测试方法,并生成两个patient对象,设置其状态并将其信息显示在屏幕上。声明并测试toString方法显示一个病人的age、sex、name及allergies属
时间: 2023-06-27 22:01:54 浏览: 573
下面是声明和实现Patient类的代码:
```java
public class Patient {
private String name;
private char sex;
private int age;
private float weight;
private boolean allergies;
public Patient(String name, char sex, int age, float weight, boolean allergies) {
this.name = name;
this.sex = sex;
this.age = age;
this.weight = weight;
this.allergies = allergies;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public boolean hasAllergies() {
return allergies;
}
public void setAllergies(boolean allergies) {
this.allergies = allergies;
}
public String toString() {
return "Name: " + name + ", Sex: " + sex + ", Age: " + age + ", Allergies: " + allergies;
}
}
```
下面是测试类的代码:
```java
public class PatientTest {
public static void main(String[] args) {
Patient p1 = new Patient("John", 'M', 35, 70.5f, false);
Patient p2 = new Patient("Jane", 'F', 27, 58.2f, true);
System.out.println("Patient 1: " + p1.toString());
System.out.println("Patient 2: " + p2.toString());
p1.setAllergies(true);
p2.setWeight(62.8f);
System.out.println("Patient 1 updated: " + p1.toString());
System.out.println("Patient 2 updated: " + p2.toString());
}
}
```
输出结果为:
```
Patient 1: Name: John, Sex: M, Age: 35, Allergies: false
Patient 2: Name: Jane, Sex: F, Age: 27, Allergies: true
Patient 1 updated: Name: John, Sex: M, Age: 35, Allergies: true
Patient 2 updated: Name: Jane, Sex: F, Age: 27, Allergies: true
```
可以看到,我们成功地创建了两个Patient对象,并且能够设置和获取它们的属性。同时,我们也测试了toString方法,能够正确地显示一个病人的信息。
阅读全文