以Person类为父类,完成Teacher子类和Worker子类的代码编写并编写一个Main类以测试Teacher子类和Worker子类代码的正确性。要求使用继承和super关键字,使编写的代码更为简洁和清晰。
时间: 2023-03-28 22:02:21 浏览: 129
好的,我可以回答这个问题。以下是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 int getAge() {
return age;
}
}
```
以下是Teacher子类的代码:
```
public class Teacher extends Person {
private String subject;
public Teacher(String name, int age, String subject) {
super(name, age);
this.subject = subject;
}
public String getSubject() {
return subject;
}
}
```
以下是Worker子类的代码:
```
public class Worker extends Person {
private String company;
public Worker(String name, int age, String company) {
super(name, age);
this.company = company;
}
public String getCompany() {
return company;
}
}
```
以下是Main类的代码:
```
public class Main {
public static void main(String[] args) {
Teacher teacher = new Teacher("张老师", 30, "数学");
System.out.println("姓名:" + teacher.getName() + ",年龄:" + teacher.getAge() + ",科目:" + teacher.getSubject());
Worker worker = new Worker("李工", 25, "XX公司");
System.out.println("姓名:" + worker.getName() + ",年龄:" + worker.getAge() + ",公司:" + worker.getCompany());
}
}
```
以上代码使用了继承和super关键字,使代码更为简洁和清晰。
阅读全文