多态的理解:我认为就是在有父类和子类之后,有向上转型的运用,向上转型是 父类引用 子类的对象。
抽象理解就是 同一行为的在不同情景下的不同表现形式,表现效果。
如Shape shape = new triangle();
有向下转型,只是用得少,前提是子类和父类已经存在联系了,也就是子类已经向上转型了。
菜鸟教程中:
多态存在的三个条件:继承,重写,父类引用指向子类对象。
对接口:接口引用指向实现类实例
有个面试题: 各个序号的输出结果是什么?
package com.judy.demo;
public class OTest {
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(a1.show(b)); // ①
System.out.println(a1.show(c)); // ②
System.out.println(a1.show(d)); // ③
System.out.println(a2.show(b)); // ④
System.out.println(a2.show(c)); // ⑤
System.out.println(a2.show(d)); // ⑥
System.out.println(b.show(b)); // ⑦
System.out.println(b.show(c)); // ⑧
System.out.println(b.show(d)); // ⑨
}
}
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,执行A中的方法:
A and A //B类不能自动转向D类,执行A类的子类,A类对象指向子类B可以。
A and A //C类是B类的子类,向上转型到A类可以。
A and D //没有转型,就是传入D类对象,类型匹配
向上转型,实例化对象是B类:
B and A //
B and A
A and D
以B类为父类了,
B and B
B and B
A and D
ps:我是执行程序看了结果才能分析原因的,结果把自己分析晕了,不看这个程序了,要疯,心好烦,/哭