定义一个接口Person,声明相关的属性和方法,再用Teacher类和Student类去继承这个接口
时间: 2024-02-17 10:04:36 浏览: 91
好的,以下是接口Person的定义:
```java
public interface Person {
String getName(); // 获取姓名
int getAge(); // 获取年龄
void setName(String name); // 设置姓名
void setAge(int age); // 设置年龄
}
```
接下来是Teacher类和Student类的定义:
```java
public class Teacher implements Person {
private String name;
private int age;
private String subject;
public Teacher(String name, int age, String subject) {
this.name = name;
this.age = age;
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@Override
public String getName() {
return name;
}
@Override
public int getAge() {
return age;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setAge(int age) {
this.age = age;
}
}
public class Student implements Person {
private String name;
private int age;
private String major;
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
@Override
public String getName() {
return name;
}
@Override
public int getAge() {
return age;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setAge(int age) {
this.age = age;
}
}
```
Teacher和Student类都实现了Person接口,并且实现了接口中的方法。这样可以保证Teacher和Student都拥有Person接口中定义的属性和方法。
阅读全文