List<Integer> list = new ArrayList<>();
变量类型为List,而不是ArrayList,这就是多态。
多态可以理解为:一个接口,多个实现类。List是一个接口,ArrayList为他的一个实现方法,还有别的实现方法LinkedList和Vector。
如果实现类实现了接口的方法,该如何调用?
经典例子:摘自深入理解java多态性_thinkGhoster的博客-CSDN博客
public class A {
public String show(D obj) {
return ("A and D");
}
public String show(A obj) {
return ("A and A");
}
}
public class B extends A{
public String show(B obj){
return ("B and B");
}
public String show(A obj){
return ("B and A");
}
}
public class C extends B{
}
public 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));
System.out.println("2--" + a1.show(c));
System.out.println("3--" + a1.show(d));
System.out.println("4--" + a2.show(b));
System.out.println("5--" + a2.show(c));
System.out.println("6--" + a2.show(d));
System.out.println("7--" + b.show(b));
System.out.println("8--" + b.show(c));
System.out.println("9--" + b.show(d));
}
}
输出结果:
1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D
调用方式:
this.show(O)-->super.show(O)--->this.show((super)O)--->super.show((super)O)
1、this.show(O)。先调用当前对象的show方法,A a2 = new B(); this就是A。如果this找不到对应方法
2、super.show(O)。再调用this的父类,也就是super的show方法。很明显A的父类是没有这个方法的,因为父类是Object,show方法是我们自己定义的。super也找不着
3、this.show((super)O)。再看传递的参数类型,a2.show(b)); 传递的是B类型,而B类型的父类是A,所以调用this.show(A),但是!!!A a2 = new B();哦哦哦所以还得看看B类有没有重写A的方法。哎,重写了就调用重写的。那么就输出B and A。。。如果还是没找到对应的方法
4、那就只能看super.show((super)O)了,道理与3一样。