编写Person类,具备属性name、age,编写两个子类Student和Teacher类,Student类除了继承父类的属性,还有属性成绩score,Teacher类还有属性工资sal。定义它们各自的构造方法(使用super),并重写Object类的toString()方法,返回属性值拼接的字符串。在测试类里创建子类对象,并调用各自的toString()方法
时间: 2024-03-10 22:49:11 浏览: 72
python面向对象进阶之路
下面是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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
// Student类
public class Student extends Person {
private int score;
public Student(String name, int age, int score) {
super(name, age);
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + super.getName() + '\'' +
", age=" + super.getAge() +
", score=" + score +
'}';
}
}
// Teacher类
public class Teacher extends Person {
private double sal;
public Teacher(String name, int age, double sal) {
super(name, age);
this.sal = sal;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + super.getName() + '\'' +
", age=" + super.getAge() +
", sal=" + sal +
'}';
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Person person = new Person("张三", 20);
System.out.println(person);
Student student = new Student("李四", 18, 85);
System.out.println(student);
Teacher teacher = new Teacher("王五", 30, 8000);
System.out.println(teacher);
}
}
```
在测试类中,我们分别创建了一个 Person 对象、一个 Student 对象和一个 Teacher 对象,并调用了它们各自的 toString() 方法,输出它们的属性值。由于 Student 和 Teacher 类都继承了 Person 类,因此它们也可以使用 super 关键字来访问父类中的属性和方法。
阅读全文