动态绑定就是在运行时自动地选择调用哪个方法的现象。
package JavaTest;
/**
*
* 员工类Employee,定义了getSalary方法获取工资
* 经理类Manager 重写了getSalary方法,因为经理不仅有工资还有奖金
*/
public class Binging {
public static void main(String[] args) {
//定义一个员工类的数组
Employee[] emp = new Employee[3];
emp[0] = new Employee(4000);
//加入一个经理类对象
emp[1] = new Manager(6000,500);
emp[2] = new Employee(3000);
//对象变量e会自动根据自身的类型调用相应的方法,员工类调用员工的getSalary方法,经理类调用经理的getSalary方法。
//这个现象就叫是动态绑定
for(Employee e:emp){
System.out.println(e.getSalary());
}
}
}
//员工类
class Employee{
//工资
private double salary;
public Employee(double salary){
this.salary = salary;
}
public double getSalary(){
return this.salary;
}
}
class Manager extends Employee{
//奖金
private double bonus;
public Manager(double salary,double bonus){
super(salary);
this.bonus = bonus;
}
public double getSalary(){
return super.getSalary()+this.bonus;
}
} |