java-多态的理解

2020-09-01  本文已影响0人  有腹肌的豌豆Z

什么是多态

上菜

public class A {

    public String show(D obj) {              //方法一
        return ("A and D");
    }

    public String show(A obj) {              //方法二
        return ("A and A");
    }

    static class B extends A {

        public String show(B obj) {              //方法三
            return ("B and B");
        }

        public String show(A obj) {              //方法四
            return ("B and A");
        }
    }

    static class C extends B {

    }

    static class D extends B {

    }


    public static void main(String[] args) {
        A a2 = new B();

        A a1 = new A();
        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));

        // 创建了B对象 类型是A ,调用超类函数,子类重写了 调用子类的
        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));
        
        System.out.println("10--" + d.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
10--A and D

让我们分析一下,理清其中各个类的继承关系

上一篇 下一篇

猜你喜欢

热点阅读