一道多态题

比较流行的一道多态题

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 {}

public class Main {
    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)); //1
        System.out.println(a1.show(c)); //2
        System.out.println(a1.show(d)); //3
        System.out.println(a2.show(b)); //4
        System.out.println(a2.show(c)); //5
        System.out.println(a2.show(d)); //6
        System.out.println(b.show(b));  //7
        System.out.println(b.show(c));  //8
        System.out.println(b.show(d));  //9
    }
}

1:this.show(b) => this.show(B obj) => this.show(A obj) => A and A

2:this.show(c) => this.show(C obj) => this.show(B obj) => this.show(A obj) => A and A

3:this.show(d) => this.show(D obj) => A and D

4:this.show(b) => this.show(B obj) => this.show(A obj) => 被B覆盖 => this.show(A obj) => B and A

5:this.show(c) => this.show(C obj) => this.show(B obj) => this.show(A obj) => 被B覆盖 => this.show(A obj) => B and A

6:this.show(d) => this.show(D obj) => B无法覆盖 => A and D

7:this.show(b) => this.show(B obj) => B and B

8:this.show(c) => this.show(C obj) => this.show(B obj) => B and B

9:this.show(d) => super.show(d) => A and D

发表回复