父类Employee
public class Employee { private String name; private int id; private double salary;
//gettters and setters ommited here public Employee(String name, int id, double salary) { this.name = name; this.id = id; this.salary = salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ",salary=" + salary + "]";
}
}
子类Manager
public class Manager extends Employee{ private double bonus; public Manager(String name, int id, double salary,int bonus) { super(name, id, salary); this.bonus=bonus;
}
public double getSalary(){
double baseSalary=super.getSalary(); return (baseSalary+baseSalary*(bonus/100));
}
@Override
public String toString() {
return "Manager [name=" + getName() + ", id=" + getId() + ", salary=" + getSalary() + ", bonus=" + bonus + "]";
}
}
还有一种方式,就是将父类的private变量改为protected,这样子类就可以直接访问父类的成员变量,就是替代了getter来访问。