2.(学号尾号为1340同)编写一个Family类,里面有三个家庭成员(father motherchild类对象)、寝室号等属性,以及寝室挑选某同学打扫卫生的动作。编写一个people类,包含:姓名、年龄、审稿等属性,以及吃饭、睡觉等动作。 在第三个Test 类中,创建1个家庭和3名同学,要求有你本人,本人姓名和学号必须是真实的。并让3个人在选出 1个人打扫卫生(推荐使用多态)。用java编程
时间: 2024-03-14 12:46:46 浏览: 71
好的,以下是代码实现:
Family类:
```java
public class Family {
private Father father;
private Mother mother;
private Child child;
private String dormitory;
public Family(Father father, Mother mother, Child child, String dormitory) {
this.father = father;
this.mother = mother;
this.child = child;
this.dormitory = dormitory;
}
public void chooseCleaner() {
System.out.println("在寝室" + dormitory + "中选择一个人打扫卫生:");
People[] people = {father, mother, child};
int randomIndex = (int) (Math.random() * 3);
People cleaner = people[randomIndex];
System.out.println(cleaner.getName() + "被选为打扫卫生的人!");
}
}
```
Father类:
```java
public class Father extends People {
public Father(String name, int age, String position) {
super(name, age, position);
}
}
```
Mother类:
```java
public class Mother extends People {
public Mother(String name, int age, String position) {
super(name, age, position);
}
}
```
Child类:
```java
public class Child extends People {
public Child(String name, int age, String position) {
super(name, age, position);
}
}
```
People类:
```java
public class People {
private String name;
private int age;
private String position;
public People(String name, int age, String position) {
this.name = name;
this.age = age;
this.position = position;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getPosition() {
return position;
}
public void eat() {
System.out.println(name + "在吃饭!");
}
public void sleep() {
System.out.println(name + "在睡觉!");
}
}
```
Test类:
```java
public class Test {
public static void main(String[] args) {
Father father = new Father("张三", 40, "父亲");
Mother mother = new Mother("李四", 35, "母亲");
Child child = new Child("王五", 10, "孩子");
Family family = new Family(father, mother, child, "301");
People[] people = {father, mother, child, new People("赵六", 20, "同学"), new People("钱七", 21, "同学"), new People("孙八", 22, "同学")};
for (People person : people) {
System.out.print(person.getName() + " ");
person.eat();
person.sleep();
}
family.chooseCleaner();
}
}
```
上述代码采用了面向对象的思想,将家庭成员和同学的属性和行为封装到了相应的类中,并在Test类中进行实例化和调用。其中,通过多态的方式,使得可以随机选择一个人进行打扫卫生。
阅读全文