设计一个抽象类名字为 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 16:34:20 浏览: 17
以下是您所描述的Person抽象类以及其子类Student和Employee的实现:
```java
abstract class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Name: " + name;
}
}
class Student extends Person {
private String status;
public static final String FRESHMAN = "Freshman";
public static final String SOPHOMORE = "Sophomore";
public static final String JUNIOR = "Junior";
public static final String SENIOR = "Senior";
public Student(String name, String status) {
super(name);
this.status = status;
}
public String getStatus() {
return status;
}
@Override
public String toString() {
return super.toString() + ", Status: " + status;
}
}
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 super.toString() + ", Office: " + office + ", Salary: " + salary;
}
}
public class Main {
public static void main(String[] args) {
Person[] people = new Person[2];
people[0] = new Student("Alice", Student.SOPHOMORE);
people[1] = new Employee("Bob", "A101", 50000.0);
for (Person person : people) {
System.out.println(person.toString());
}
}
}
```
在上述代码中,我们定义了抽象类Person,并在其子类Student和Employee中实现了各自的属性和构造方法。Person类包含一个name属性和toString方法。Student类有一个status属性,定义了常量值作为status的选项,并重写了toString方法。Employee类有一个office属性和salary属性,并重写了toString方法。
在主函数中,我们创建了一个Person类型的数组,并存放了一个Student对象和一个Employee对象。通过多态性,我们调用了toString方法打印出每个对象的属性信息。注意,为了简化代码,只为name属性编写了get和set方法。其他属性的get和set方法可以按照相同的方式添加。