设计一个抽象类名字为 Person,它的子类为Student和 Employee;person类有name以及toString方法;student有 status属性(freshman, sophomore, junior, or senior),定义status 为常量;Employee类 有office, salary;分别定义各个类的有参构造方法,Person(String name)、Student(String name,int status)、Employee(String name,String office,double salary),注意需要在子类构造方法第一句调用父类有参构造方法,为子类也实现toString方法。编写测试类定义一个数组存放每个非抽象类对象(Student和 Employee),然后利用多态调用toString方法打印各个对象的所有属性信息。(为了减少书写量,只需要为name属性完成get和set方法,其他属性不用写)
时间: 2024-04-08 15:35:12 浏览: 128
以下是符合要求的Java代码:
```java
// Person抽象类
abstract class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract String toString();
}
// Student类
class Student extends Person {
private static final int FRESHMAN = 1;
private static final int SOPHOMORE = 2;
private static final int JUNIOR = 3;
private static final int SENIOR = 4;
private int status;
public Student(String name, int status) {
super(name);
this.status = status;
}
public String getStatus() {
String statusStr = "";
switch (status) {
case FRESHMAN:
statusStr = "Freshman";
break;
case SOPHOMORE:
statusStr = "Sophomore";
break;
case JUNIOR:
statusStr = "Junior";
break;
case SENIOR:
statusStr = "Senior";
break;
}
return statusStr;
}
@Override
public String toString() {
return "Name: " + getName() + ", Status: " + getStatus();
}
}
// Employee类
class Employee extends Person {
private String office;
private double salary;
public Employee(String name, String office, double salary) {
super(name);
this.office = office;
this.salary = salary;
}
public String getOffice() {
return office;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Name: " + getName() + ", Office: " + getOffice() + ", Salary: " + getSalary();
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Person[] people = new Person[4];
people[0] = new Student("Alice", 2);
people[1] = new Student("Bob", 4);
people[2] = new Employee("Charlie", "A101", 5000.0);
people[3] = new Employee("Dave", "B202", 7000.0);
for (Person person : people) {
System.out.println(person.toString());
}
}
}
```
这段代码定义了抽象类 `Person` 和它的两个子类 `Student` 和 `Employee`。`Person` 类有一个 `name` 属性和 `toString` 方法。`Student` 类有一个 `status` 属性(使用常量表示学生的年级)和相应的 `toString` 方法。`Employee` 类有一个 `office` 属性和一个 `salary` 属性,以及相应的 `toString` 方法。测试类 `Test` 创建了一个包含不同类型对象的数组,并利用多态调用 `toString` 方法打印各个对象的属性信息。
阅读全文