4、定义一个抽象的Role类有姓名年龄性别等成员变量1要求尽可能隐藏所有变量能够私有就私有能够保护就不要公有再通过GetXXX和SetXXX方法对各变量进行读写。具有一个抽象的play方法该方法不返回任何值同时至少定义两个构造方法。Role类中要体现出this的几种用法。2从Role类派生出一个Employee类该类具有Role类的所有成员构造方法除外并扩展salary成员变量同时增加一个静态成员
// Role类
public abstract class Role {
private String name;
private int age;
private String gender;
public Role() {
System.out.println("Role类的无参构造方法");
}
public Role(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
System.out.println("Role类的有参构造方法");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public abstract void play();
}
// Employee类
public class Employee extends Role {
private double salary;
private static int ID;
public Employee() {
System.out.println("Employee类的无参构造方法");
}
public Employee(String name, int age, String gender, double salary) {
super(name, age, gender);
this.salary = salary;
System.out.println("Employee类的有参构造方法");
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public static int getID() {
return ID;
}
public static void setID(int ID) {
Employee.ID = ID;
}
@Override
public void play() {
System.out.println("Employee正在玩耍");
}
public final void sing() {
System.out.println("Employee正在唱歌");
}
}
// Manager类
public class Manager extends Employee {
private final String vehicle;
public Manager() {
System.out.println("Manager类的无参构造方法");
vehicle = "Car";
}
public Manager(String name, int age, String gender, double salary, String vehicle) {
super(name, age, gender, salary);
this.vehicle = vehicle;
System.out.println("Manager类的有参构造方法");
}
@Override
public void play() {
System.out.println("Manager正在玩耍");
}
public String getVehicle() {
return vehicle;
}
public void drive() {
System.out.println("Manager正在开车");
}
}
// 测试
public class Main {
public static void main(String[] args) {
Role role = new Employee("张三", 25, "男", 5000);
role.play();
Employee employee = new Employee("李四", 30, "女", 6000);
employee.play();
employee.sing();
Manager manager = new Manager("王五", 35, "男", 10000, "BMW");
manager.play();
manager.sing();
manager.drive();
}
}
输出结果:
Role类的有参构造方法
Employee类的有参构造方法
Employee正在玩耍
Role类的有参构造方法
Employee类的有参构造方法
Employee正在玩耍
Employee正在唱歌
Role类的有参构造方法
Employee类的有参构造方法
Manager类的有参构造方法
Manager正在玩耍
Employee正在唱歌
Manager正在开车
原文地址: https://www.cveoy.top/t/topic/i4KU 著作权归作者所有。请勿转载和采集!