java定义一个Person抽象类,包含姓名和年龄两个属性,以及一 个抽象方法work()。定义Employee类继承Person类,并实 现自己特有的work()方法,定义Student类继承Person类, 并实现自己特有的study()方法的测试类
时间: 2023-06-16 15:08:05 浏览: 121
下面是Java代码实现:
```java
abstract 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;
}
public abstract void work();
}
class Employee extends Person {
public Employee(String name, int age) {
super(name, age);
}
@Override
public void work() {
System.out.println("I am an employee and I work in the company.");
}
}
class Student extends Person {
public Student(String name, int age) {
super(name, age);
}
@Override
public void work() {
System.out.println("I am a student and I study in the school.");
}
public void study() {
System.out.println("I am a student and I am studying now.");
}
}
public class Test {
public static void main(String[] args) {
Person p1 = new Employee("Tom", 30);
Person p2 = new Student("Jerry", 20);
System.out.println(p1.getName() + ", " + p1.getAge());
p1.work();
System.out.println(p2.getName() + ", " + p2.getAge());
p2.work();
((Student) p2).study(); // 强制类型转换,调用子类特有的方法
}
}
```
运行结果:
```
Tom, 30
I am an employee and I work in the company.
Jerry, 20
I am a student and I study in the school.
I am a student and I am studying now.
```
阅读全文