Java多态--- 如何匹配的呢?

来源:互联网 发布:ubuntu的浏览器字体 编辑:程序博客网 时间:2024/06/14 08:38

题目如下
这里写图片描述

匹配原则:

先: 确保参数完全匹配O的前提下,依次匹配this与super。
再: 考虑参数用super(O)渐近匹配O,依次匹配this与super
当: 存在子类覆盖父类方法时,根据new子类实例的原则,先调子类方法。

匹配顺序:

this.show( O )  super.show( O )  this.show( super(O) )  super.show( super(O) )

A a = new B(); 等于号左边决定 选择哪个参数 等号右边选择方法, new 谁调谁, 没有再我、去父类找。

package Studying;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");       }       public String show(D obj){          return ("B and D");     }   }  class C extends B{}   class D extends B{}class E extends D{}public class TestDT{    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();       E e = new E();     System.out.println( a2.show(d));//        System.out.println(a1.show(b)); //  ①  A and A//        System.out.println(a1.show(c)); //  ②  A and A//        System.out.println(a1.show(d)); //  ③  A and D//        System.out.println(a2.show(b)); //  ④  B and A//        System.out.println(a2.show(c)); //  ⑤  B and A//        System.out.println(a2.show(d)); //  ⑥  A and D//        System.out.println(b.show(b));  //  ⑦  B and B//        System.out.println(b.show(c));  //  ⑧  B and B//        System.out.println(b.show(d)); //  ⑨  A and D//    }}
原创粉丝点击