Java 多态
多态是同一个行为具有多个不同表现形式或形态的能力。
多态的优点
- 1. 消除类型之间的耦合关系
- 2. 可替换性
- 3. 可扩充性
- 4. 接口性
- 5. 灵活性
- 6. 简化性
多态存在的三个必要条件
- 继承
- 重写
- 父类引用指向子类对象:Parent p = new Child();
Java 多态的经典例子
继承链中对象方法的调用例子
demo中继承关系图如下:
入口类
package com.other;
import org.junit.Test;
/**
*所以多态机制遵循的原则概括为:当超类对象引用变量引用子类对象时,
* 被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,
* 但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法,
* 但是它仍然要根据继承链中方法调用的优先级来确认方法,
* 该优先级为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。
*/
public class Client {
@Test
public void test(){
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
E e = new E();
//继承链调用优先级:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)
System.out.println("1:"+a1.show(b));//1:class A and paramter A -> this.show((super)O)
System.out.println("2:"+a1.show(c));//2:class A and paramter A -> this.show((super)O)
System.out.println("3:"+a1.show(d));//3:class A and paramter D -> this.show(O)
//a2的被引用对象类型为B,引用变量类型为A,B决定了调用谁的方法
//它仍然要根据继承链中方法调用的优先级来确认方法
System.out.println("4:"+a2.show(b));//4:class B and paramter A -> this.show(O)
System.out.println("5:"+a2.show(c));//5:class B and paramter A -> this.show(O)
System.out.println("6:"+a2.show(d));//6:class A and paramter D -> super.show(O)
//继承链调用优先级:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)
System.out.println("7:"+b.show(b));//7:class B and paramter B -> this.show(O)
System.out.println("8:"+b.show(c));//8:class B and paramter B -> this.show((super)O)
System.out.println("9:"+b.show(d));//9:class A and paramter D -> super.show(O)
System.out.println("10:"+b.show(a2));//10:class B and paramter A -> this.show(O)
System.out.println("11:"+e.show(b));//11:class A and paramter A -> super.show((super)O)
}
}
父类A
package com.other;
public class A {
public String show(D obj){
return "class A and paramter D";
}
public String show(A obj){
return "class A and paramter A";
}
}
子类B
package com.other;
public class B extends A {
public String show(B obj){
return "class B and paramter B";
}
public String show(A obj){
return "class B and paramter A";
}
}
子子类C
package com.other;
public class C extends B {
}
子子类D
package com.other;
public class D extends B {
}
子类E
package com.other;
public class E extends A {
}
通过打印结果可知,多态机制遵循的原则概括为:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法,但是它仍然要根据继承链中方法调用的优先级来确认方法,该优先级为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。