多态的经典问题
来源:互联网 发布:淘宝增值服务有哪些 编辑:程序博客网 时间:2024/06/05 03:19
Java多态有关的一个经典问题
public class hello { 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)); }}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{}
解释
a1.show(b));Class A 中没有show(B obj),B转向B的父类A,执行A show(A obj)—>return “A and A”
a1.show(c));Class A 中没有show(C obj),C转向C的父类B,Class A 中没有show(B obj),再转向父类A,执行A show(A obj)—>return “A and A”
a1.show(d));Class A 中有show(D obj)执行A show(D obj)—>return “A and D”
这个比较特殊:A a2 = new B();父类声明,子类实例,你应该把a2当作子类重写完后的父类看,注意只有父类的方法。
a2.show(b));Class A 中没有show(B obj),B转向B的父类A,执行A show(A obj),A的show 方法被重写,执行B show(A obj)—>return “B and A”
a2.show(c));Class A 中没有show(C obj),C转向C的父类B,Class A 中没有show(B obj),B转向父类A,执行A show(A obj),A的show 方法被重写,执行B show(A obj)—>return “B and A”
a2.show(d));Class A 中有show(D obj)执行A show(D obj)—>return “A and D”
b.show(b)); Class B 中有show(B obj)—>return “B and B”
b.show(c)); Class B 中没有show(C obj),C转向C的父类B,执行B show(B obj)—>return “B and B”
b.show(d)); Class B 中有继承了Class A 的show(D obj),执行A show(D obj)—>return “A and D”
- 多态的经典问题
- 经典的简单多态的调用问题
- 经典的分配问题12态
- 经典的海盗问题
- 面试的经典问题
- 经典的字符串问题
- 一个经典的问题
- 面试的经典问题
- 经典的猴子问题
- 经典的回溯问题
- 经典的兔子问题
- 经典的汉诺塔问题
- 经典的报数问题
- Spring的经典问题
- 打表法的经典问题
- 十个面试经典问题的经典回答
- 九个经典面试问题的经典回答
- 人生的八个经典问题
- 解决macbook pro在只有win8系统下开启AHCI的问题
- 动态代理hook自己进程的startActivity方法
- HDU 2485 Destroying the bus stations(最小割)
- 阿里-2018 c++ 第一题
- 博客格式测试
- 多态的经典问题
- easyui精简版教程 10分钟上手
- 1355 斐波那契的最小公倍数
- 校园招聘-2017阿里C/C++研发工程师内推笔试编程题
- VS恢复默认设置
- 第二十六天总结
- java学习——java基础(九)之序列化
- HDU 6172 Array Challenge (打表找规律+矩阵快速幂 17多校第十场第2题)
- <<Linux达人养成计划二>>学习笔记