用java设计校园生活模拟程序。 声明一个Person抽象类,并且定义三个初始属性:学习值,富裕值,快乐值,并且三个值初始都为60,上限为100,下限为0。然后派生出Teacher和Student类,Student再派生出UndergraduateStudent和GraduateStudent。以上类都继承Person所有属性。 Person类中声明3个抽象方法:work()该方法能增加5点学习值,增加1点富裕值,减少3点快乐值、earn()该方法能增加1点学习值,增加5点富裕值,减少5点快乐值、enjoy()该方法能减少5点学习值,减少10点富裕值,增加10点快乐值。main方法中生成若干教师、本科生、研究生对象,或生成对象数组,进行功能测试,并输出三个值大小。
时间: 2024-02-13 11:07:05 浏览: 99
好的,这是一个很好的面向对象设计题目。我将给出Java代码实现:
```java
public abstract class Person {
protected int studyValue;
protected int wealthValue;
protected int happinessValue;
public Person() {
this.studyValue = 60;
this.wealthValue = 60;
this.happinessValue = 60;
}
public abstract void work();
public abstract void earn();
public abstract void enjoy();
public int getStudyValue() {
return studyValue;
}
public int getWealthValue() {
return wealthValue;
}
public int getHappinessValue() {
return happinessValue;
}
}
public class Teacher extends Person {
public void work() {
this.studyValue += 5;
this.wealthValue += 1;
this.happinessValue -= 3;
checkValueRange();
}
public void earn() {
this.studyValue += 1;
this.wealthValue += 5;
this.happinessValue -= 5;
checkValueRange();
}
public void enjoy() {
this.studyValue -= 5;
this.wealthValue -= 10;
this.happinessValue += 10;
checkValueRange();
}
private void checkValueRange() {
this.studyValue = Math.min(Math.max(this.studyValue, 0), 100);
this.wealthValue = Math.min(Math.max(this.wealthValue, 0), 100);
this.happinessValue = Math.min(Math.max(this.happinessValue, 0), 100);
}
}
public class Student extends Person {
public void work() {
this.studyValue += 5;
this.wealthValue += 1;
this.happinessValue -= 3;
checkValueRange();
}
public void earn() {
this.studyValue += 1;
this.wealthValue += 5;
this.happinessValue -= 5;
checkValueRange();
}
public void enjoy() {
this.studyValue -= 5;
this.wealthValue -= 10;
this.happinessValue += 10;
checkValueRange();
}
private void checkValueRange() {
this.studyValue = Math.min(Math.max(this.studyValue, 0), 100);
this.wealthValue = Math.min(Math.max(this.wealthValue, 0), 100);
this.happinessValue = Math.min(Math.max(this.happinessValue, 0), 100);
}
}
public class UndergraduateStudent extends Student {
}
public class GraduateStudent extends Student {
}
public class Main {
public static void main(String[] args) {
Person[] people = new Person[5];
people[0] = new Teacher();
people[1] = new UndergraduateStudent();
people[2] = new GraduateStudent();
people[3] = new Teacher();
people[4] = new UndergraduateStudent();
for (Person person : people) {
person.work();
person.earn();
person.enjoy();
System.out.println("学习值:" + person.getStudyValue() + ",富裕值:" + person.getWealthValue() + ",快乐值:" + person.getHappinessValue());
}
}
}
```
以上代码实现了面向对象的设计思想,将抽象类 Person 作为基础类,派生出 Teacher 和 Student 类,再从 Student 中派生出 UndergraduateStudent 和 GraduateStudent 类。Person 类中定义了三个抽象方法,派生类必须实现这些方法,以完成不同的功能。
在 Main 类中,我们创建了一个 Person 类型的数组,其中存放了不同类型的对象。我们通过遍历数组,调用每个对象的 work()、earn() 和 enjoy() 方法来改变对象的属性值,并输出结果。
阅读全文