基类的引用可以指向派生类的对象,如:
Person person = new Student();
这样的语句是合法的;
但是派生类的引用则不可以指向基类的对象,如:
Student st = new Person();
这样的语句将引发错误。
示例
class A {
public String show(D obj){
return ("A and D");
}
public String show(A obj)...{
return ("A and A");
} }
class B extends A{
public String show(B obj)...{
return ("B and B");
}
public String show(A obj)...{
return ("B and A");
} }
class C extends B...{} class D extends B...{}
问题:以下输出结果是什么?
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println(a1.show(b)); ① A and A
System.out.println(a1.show(c)); ② A and A
System.out.println(a1.show(d)); ③ A and D
System.out.println(a2.show(b)); ⑤ B and A
System.out.println(a2.show(c)); ⑤ B and A
System.out.println(a2.show(d)); ⑥ A and D
System.out.println(b.show(b)); ⑦ B and B
System.out.println(b.show(c)); ⑧ B and B
System.out.println(b.show(d)); ⑨ A and D
从上例中可以看出,父类的引用指向哪个类的实例就调用哪个类中的方法;
同样是使用父类的引用,调用同一个名称的方法,却可以得到不同的调用结果,这就是Java中的多态,即: 同一函数,多种形态;