本文共 1540 字,大约阅读时间需要 5 分钟。
多态与继承结合知识点
package sdada; class A { private String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } public String show(B obj) { return ("ddad"); } } class B extends A { public String show(B obj) { return ("B and B"); } public String show(A obj) { return ("B and A"); } public String showshao(A obj) { return ("A and A"); } } class C extends B { } class D extends B { } public class dadsad { 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)); } }输出 ddadddadddadB and BB and BB and BB and BB and BB and B 但是将A前的private改为public,结果是 ddadddadA and DB and BB and BA and DB and BB and BA and D观点: A类引用指向B类对象时,调用的方法一定是A、B共有的,若只有B有A没有则编译出错,若只有A有则A应该是非private的,否则会出错,在该程序中就是改成private后会匹配其他的类型了,同样,根据多态选择调用哪个方法不是根据代码中的先后顺序而是根据亲疏关系,例如C extends B,B extends A,则C作为参数寻找多态时,先匹配B再匹配A而不管先后顺序
转载地址:http://ruonn.baihongyu.com/