1、员工类:
public abstract class Employee {
//名字
private String name;
//编号
private int id;
//薪水
private double salary;
//无参构造
public Employee(){
}
//有参构造
public Employee(String name,int id, double salary){
this.name = name;
this.id = id;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return getName()+"{"+",id:" + getId()+",salary:"+getSalary()+'}';
}
//抽象类方法:work()
public abstract void work();
}
2、经理类:
public class Manager extends Employee {
//经理的奖金
private double bonus;
//无参构造
public Manager(){
}
//有参构造1
public Manager(double bonus){
//可通过super直接赋值 这样更简便
super("li",123,2000.0);
this.bonus = bonus;
}
//有参构造 自己赋值
public Manager(String name,int id,double salary,double bonus){
super(name,id,salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
//抽象方法的实现
public void work(){
System.out.println(getName()+"经理工作中");
}
@Override
public String toString() {
return getName()+"{" + "bonus:" + bonus +",id:" + getId()+",salary:"+getSalary()+'}';
}
}
3、测试类:
public class EmployeeTest {
public static void main(String[] args) {
//创建员工对象 而且是一个经理
Employee e1 = new Manager(1000.0);
//重写过Manager类的toString方法 可直接输出e1的所有信息
System.out.println(e1);
//调用Manager类的work()方法
e1.work();
}
}
4、输出结果:
li{bonus:1000.0,id:123,salary:2000.0}
li经理工作中
Process finished with exit code 0