多态的实现机制
基于继承和接口实现的多态机制主要表现在父类和继承该父类的一个或多个子类对某些方法的重写,多个子类对同一方法的重写可以表现出不同的行为。多态:多种形态,就是多态性
多态规则
指向子类的父类引用由于向上转型了,它只能访问父类中拥有的方法和属性,而对于子类中存在而父类中不存在的方法,该引用是不能使用的,尽管是重载该方法。若子类重写了父类中的某些方法,在调用该些方法的时候,必定是使用子类中定义的这些方法,他们优先级高于父类中的方法。
多态的经典例子
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{
}
public class Test {
public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println("1--" + a1.show(b));//A and A
System.out.println("2--" + a1.show(c));//A and A
System.out.println("3--" + a1.show(d));//A and D
System.out.println("4--" + a2.show(b));//B and A
System.out.println("5--" + a2.show(c));//B and A
System.out.println("6--" + a2.show(d));//A and D
System.out.println("7--" + b.show(b));//B and B
System.out.println("8--" + b.show(c));//B and B
System.out.println("9--" + b.show(d));//A and D
}
}
继承链中对象方法的调用存在优先级
this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)
分析第5个:a2.show( c )
- this.show(O):a2是A类型的引用变量,所以this就代表了a2,a2.show©,它在A类中找发现没有找到
- super.show(O):于是到A的超类中找(super),由于A没有超类(Object除外),所以跳过
- this.show((super)O):c的超类有B、A,所以(super)O为B、A,this同样是A,这里在A中找到了show(A obj)
- 运行时类型:由于a2是B类的一个引用且B类重写了show(A obj),因此最终会调用子类B类的show(A obj)方法,结果也就是B and A。
注意
当超类对象引用变量引用子类对象时,被引用对象的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的
多态分析步骤
- this.show(O)
this指代的是编译时类型 - super.show(O)
super指代的是编译时类型的父类 - this.show((super)O)
super指代的是参数O类型的父类 - super.show((super)O)
- 查看运行时类型是否重写了改方法
以上四个步骤,先找到对应方法的直接跳到第五个步骤执行
是:执行运行时类型类中的此方法
否:执行编译时类型类中的此方法