用java语言创建一个person类,让student,teacher继承person类,在person类中,有基本属性,姓名年龄和
时间: 2024-10-23 22:08:05 浏览: 30
在Java中,我们可以创建一个名为`Person`的基础类,然后让它作为`Student`和`Teacher`两个子类的超类。下面是一个简单的示例:
```java
// Person 类
public class Person {
// 基本属性
private String name;
private int age;
// 构造函数初始化属性
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 获取和设置属性的方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 定义一个通用的行为方法,如打招呼
public void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
// 子类 Student 和 Teacher 继承 Person 类
class Student extends Person {
// 可能有的额外属性或行为
private String studentID;
public Student(String name, int age, String studentID) {
super(name, age); // 调用父类构造函数
this.studentID = studentID;
}
@Override
public void greet() {
super.greet();
System.out.println("I'm a student with ID: " + studentID);
}
}
class Teacher extends Person {
private String teacherSubject;
public Teacher(String name, int age, String teacherSubject) {
super(name, age); // 调用父类构造函数
this.teacherSubject = teacherSubject;
}
@Override
public void greet() {
super.greet();
System.out.println("I teach " + teacherSubject + " at the school.");
}
}
```
在这个例子中,`Student`和`Teacher`都继承了`Person`并重写了`greet()`方法以展示各自的特性。
阅读全文