RT.. 其中Employee为父类, Manager为Employee的子类.public class ManagerTest
{
public static void main(String[] args)
{
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[1];
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); .........
}}请问,这里boss为子类Manager的实例对像,但为什么它可以这样定义:
Employee[] staff = new Employee[1];
staff[0] = boss;
staff为父类实例对像,boss为子类实例对像. staff[0] = boss 是什么意思呢..? 父类怎么能掉用子类呢..?
{
public static void main(String[] args)
{
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[1];
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); .........
}}请问,这里boss为子类Manager的实例对像,但为什么它可以这样定义:
Employee[] staff = new Employee[1];
staff[0] = boss;
staff为父类实例对像,boss为子类实例对像. staff[0] = boss 是什么意思呢..? 父类怎么能掉用子类呢..?
我也正是看到了多态.. 但我有不解.所以发上来请教大家..
麻烦大家解释清楚,让小弟学习下.. 谢谢.
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
//fill the staff array with Manager and Employee objects;
staff[0] = new Manager("Carl Cracker", 80000, 1987, 12, 15);//这样可以.
staff[0].setBonus(7000);//但这里不行..请问这是什么?
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
//print out informaton about all Employee objects
for(int i = 0; i < staff.length; i++)
{
Employee e = staff[i];
System.out.println("name = " + e.getName() + ",salary = " + e.getSalary());
}
}
}
setBonus 是子类Manager里的一个方法.public class ManagerTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Manager("Carl Cracker", 80000, 1987, 12, 15);//这样可以.请问为什么行
staff[0].setBonus(7000); // 这里不可以这样调用..请问为什么不行?
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15); for(int i = 0; i < staff.length; i++)
{
Employee e = staff[i];
System.out.println("name = " + e.getName() + ",salary = " + e.getSalary());
}
}
}
上溯,ok
staff[0].setBonus(7000); // 这里不可以这样调用..请问为什么不行?
此时编译器只知道staff[0]是一Employee,而Employee中并没有setBonus(7000)方法,所以当然要报错了。
以后接触多了自然就习惯了