Java中的多态(polymorphism)和动态绑定(dynamic binding)

来源:互联网 发布:ff14人女捏脸数据 编辑:程序博客网 时间:2024/05/29 16:41

以下面代码为例,存在超类Employee和子类Manager,两个类中都有getSalary方法,但实现不同。

一个对象变量可以引用多种实际类型的现象被称为多态(polymorphism),运行时能够自动选择调用哪个方法的现象称为动态绑定(dynamic binding)。

Employee类型的变量e既可以引用Employee类型又可以引用Manager类型,称为多态;调用e.getSalary时,根据e所引用的实际类型,决定调用Employee.getSalary还是调用Manager.getSalary,称为动态绑定。

需要注意的是,Employee类型的变量e尽管引用了Manager类型,但是不能够调用只定义在Manager子类中的方法(如setBonus),因为编译器将e视为Employee类型。如果要调用Manager类中的方法,需另外声明Manager类型的变量(如boss)进行调用。

import java.util.*;/** * This program demonstrates inheritance. * @version 1.21 2004-02-21 * @author Cay Horstmann */public class ManagerTest {    public static void main(String[] args)   {      // construct a Manager object      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);      boss.setBonus(5000);      Employee[] staff = new Employee[3];      // fill the staff array with Manager and Employee objects      staff[0] = boss;      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);      staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);      // print out information about all Employee objects      for (Employee e : staff)         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());   }}class Employee{   public Employee(String n, double s, int year, int month, int day)   {      name = n;      salary = s;      GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);      // GregorianCalendar uses 0 for January      hireDay = calendar.getTime();   }   public String getName()   {      return name;   }   public double getSalary()   {      return salary;   }   public Date getHireDay()   {      return hireDay;   }   public void raiseSalary(double byPercent)   {      double raise = salary * byPercent / 100;      salary += raise;   }   private String name;   private double salary;   private Date hireDay;}class Manager extends Employee{    /**    * @param n the employee's name    * @param s the salary    * @param year the hire year    * @param month the hire month    * @param day the hire day    */   public Manager(String n, double s, int year, int month, int day)   {      super(n, s, year, month, day);      bonus = 0;   }   public double getSalary()   {      double baseSalary = super.getSalary();      return baseSalary + bonus;   }   public void setBonus(double b)   {      bonus = b;   }   private double bonus;}

参考:
Cay S. Horstmann, Gary Cornell. JAVA核心技术卷I:基础知识(第八版).机械工业出版社.2011年4月第1版.第5.1节.

0 0