//这是一个Employee类 import java.util.Date; import java.util.GregorianCalendar; public class Employee { private String name; private double salary; private Date hireDay; 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; } } ———————————————————————————————————————— //这是一个Manage类,继承Employee类 public class Manager extends Employee { private double bonus; public void setBonus(double b){ bonus=b; } public Manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day); bonus=0; } public double getSalary(){ return super.getSalary()+bonus; } } —————————————————————————————————————————————— //测试类 public class ManageTest { public static void main(String[] args) { Employee[] staff=new Employee[3]; Manager boss=new Manager("Carl Cracker",80000,1987,12,15); boss.setBonus(5000); staff[0]=boss; staff[1]=new Employee("Harry Hacker",50000,1989,10,1); staff[2]=new Employee("Tommy Tester",40000,1990,3,15); //首先举个例子:报错,编译器将staff[0]看做Employee对象,不允许调用Manager类对象的方法。 staff[0].setBonus(1000); /* * 那么当for循环i=0时,staff[i]调用的getSalary()为什么还是Manager类的方法,salary=85000; * 我知道“动态绑定”这个概念。但是我不懂的问题在于: * 前面已经举例了,编译器将staff[0]看作Employee对象,那么应该说明编译器不知道staff[0]是Manager对象, * 应该会调用Employee类的getSalary()方法啊。结果为什么还是调用了Manager()中的getSalary()方法? * 哪里理解错了吗? */ for(int i=0;i<staff.length;i++){ System.out.println("name="+staff[i].getName()+",salary="+staff[i].getSalary()); } } } —————————————————————————— //运行结果 name=Carl Cracker,salary=85000.0(不是我想象中的80000.0) name=Harry Hacker,salary=50000.0 name=Tommy Tester,salary=40000.0 问题在测试类的注释中。
幽凝
相关分类