2. 在同一个包 package gench 中,定义以下三个类 (1)定义一个接口 Person,其中包含一个抽象方法 public void display(); (2)定义 Person 的实现类 Teacher,以及实现类 Employee, Teacher 类包含 String sub ject数据成员和有参构造方法,Employee 类包含 String department 和有参构造方法,在两个实现类中重写 display ()方法,打印自己的数据成员信息。 (3)定义主类 MainClass,包含主两数,在主函数中定义一个接口引用,名为ob,让其分别指向 新生成的 Teacher 和 Employee 的対象,并調用 display()函数,打印所指向対象的信息
时间: 2024-03-06 11:52:20 浏览: 126
好的,我明白了您的问题。以下是代码实现:
Person 接口:
```java
package gench;
public interface Person {
public void display();
}
```
Teacher 类:
```java
package gench;
public class Teacher implements Person {
String subject;
public Teacher(String subject) {
this.subject = subject;
}
@Override
public void display() {
System.out.println("Teacher's subject: " + subject);
}
}
```
Employee 类:
```java
package gench;
public class Employee implements Person {
String department;
public Employee(String department) {
this.department = department;
}
@Override
public void display() {
System.out.println("Employee's department: " + department);
}
}
```
MainClass 类:
```java
package gench;
public class MainClass {
public static void main(String[] args) {
Person ob;
ob = new Teacher("Math");
ob.display();
ob = new Employee("IT");
ob.display();
}
}
```
运行结果:
```
Teacher's subject: Math
Employee's department: IT
```
希望能够解答您的问题!
阅读全文