java中只能继承单个类,不能有class WorkingStudent extends Student, Staff。但是你可以实现多个接口,所以我会向你推荐一个带接口的解决方案。首先让我们定义学生功能。学生必须学习,所以:
public interface Student {
void study();
}
现在对于员工来说,他显然必须工作,所以:
public interface Staff {
void work();
}
一个非常简单的person类:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
普通学生只是学习或不学习,谁知道呢,但我们假设他学习了。他是一个人,也做学生的事情。
public class NormalStudent extends Person implements Student {
public NormalStudent(String name) {
super(name);
}
@Override
public void study() {
System.out.println(getName() + " studies a lot.");
}
}
还有你的普通员工,他们没有尽职尽责。他是一个人,他做员工的事情。
public class NormalStaff extends Person implements Staff {
public NormalStaff(String name) {
super(name);
}
@Override
public void work() {
System.out.println(getName() + " does whatever the staff does");
}
}
现在对于同时也是工作人员的学生:
public class WorkingStudent extends NormalStudent implements Staff {
public WorkingStudent(String name) {
super(name);
}
@Override
public void work() {
System.out.println(getName() + " has finished studying, but does not go to the party and instead does his obligations as a staff member of his university.");
System.out.println(getName() + " has a bright future ahead of him. Probably.");
}
}
WorkingStudent 是一个 NormalStudent,也是一个 Person(他从 NormalStudent 继承了 Student 的功能和 Person 的属性),并实现了 Staff 从而获得了相应的功能。
还有一个小例子:
NormalStudent james = new NormalStudent("James");
james.study();
WorkingStudent george = new WorkingStudent("George");
george.study();
george.work();
NormalStaff john = new NormalStaff("John");
john.work();