用java实现创建一个 Person 类(父类),通过扩展创建 Student 和 Teacher 类(子类);并在主类 TestOne 里实现创建对象,成员变量的初始化、 方法调用等;
时间: 2023-05-26 12:04:31 浏览: 82
Person类代码:
```java
public class Person {
protected String name;
protected int age;
protected char gender;
public Person(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
```
Student类代码:
```java
public class Student extends Person {
private int grade;
public Student(String name, int age, char gender, int grade) {
super(name, age, gender);
this.grade = grade;
}
public void study() {
System.out.println(name + " is studying in grade " + grade + ".");
}
}
```
Teacher类代码:
```java
public class Teacher extends Person {
private String subject;
public Teacher(String name, int age, char gender, String subject) {
super(name, age, gender);
this.subject = subject;
}
public void teach() {
System.out.println(name + " is teaching " + subject + ".");
}
}
```
TestOne类代码:
```java
public class TestOne {
public static void main(String[] args) {
Person person = new Person("Tom", 20, 'M');
Student student = new Student("Bob", 18, 'M', 10);
Teacher teacher = new Teacher("Mary", 30, 'F', "Math");
person.eat();
person.sleep();
student.eat();
student.sleep();
student.study();
teacher.eat();
teacher.sleep();
teacher.teach();
}
}
```
输出结果:
```
Tom is eating.
Tom is sleeping.
Bob is eating.
Bob is sleeping.
Bob is studying in grade 10.
Mary is eating.
Mary is sleeping.
Mary is teaching Math.
```
阅读全文