编程实现类的继承。编写父类People,子类Employee继承自人类。人类具有姓名,性别,年龄等性质,还具有吃和说的行为。雇员类继承父类,还拥有工号性质和工作行为。构造人类和学生类的对象,调用吃、说、工作的方法输出有关信息。 用JAVA编写
时间: 2023-05-31 11:07:55 浏览: 237
java 2实用教程第四版_第5章_之类与继承
好的,这是一个关于面向对象编程的问题,我可以帮您解答。以下是JAVA代码实现:
```
public class People {
protected String name;
protected String gender;
protected int age;
public People(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public void eat() {
System.out.println("I am eating.");
}
public void say() {
System.out.println("I am speaking.");
}
}
public class Employee extends People {
private int employeeId;
public Employee(String name, String gender, int age, int employeeId) {
super(name, gender, age);
this.employeeId = employeeId;
}
public void work() {
System.out.println("I am working.");
}
}
public class Main {
public static void main(String[] args) {
People p = new People("Tom", "male", 25);
p.eat();
p.say();
Employee e = new Employee("Mary", "female", 30, 12345);
e.eat();
e.say();
e.work();
System.out.println("My name is " + p.name);
System.out.println("I am a(n) " + p.gender);
System.out.println("I am " + p.age + " years old.");
System.out.println("My name is " + e.name);
System.out.println("I am a(n) " + e.gender);
System.out.println("I am " + e.age + " years old.");
System.out.println("My employee ID is " + e.employeeId);
}
}
```
在这个例子中,我们定义了一个父类People以及一个子类Employee。在People类中,我们定义了姓名、性别、年龄这三个属性,并且拥有吃和说的行为。在Employee类中,我们通过继承People类,继承了这三个属性和吃、说的方法,并且增加了工号这一属性和工作这一行为。在主函数中,我们分别构造了两个对象,一个是People类的对象p,另一个是Employee类的对象e。我们对两个对象调用相应的方法,输出了与其相关的信息。
阅读全文