• java多态例子


    多态存在的三个必要条件
    一、要有继承;
    二、要有重写;
    三、父类引用指向子类对象。

    代码部分:

    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 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(a1));
            System.out.println(a1.show(a2));
            System.out.println(a2.show(a1));
            System.out.println(a2.show(a2));
            System.out.println(b.show(a1));
            System.out.println(b.show(a2));
            System.out.println(c.show(a1));
            System.out.println(c.show(a2));
            System.out.println(d.show(a1));
            System.out.println(d.show(a2));
            System.out.println("分割线**************************************");
            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));
            System.out.println(c.show(b));
            System.out.println(c.show(c));
            System.out.println(c.show(d));
    
        }

    运行结果:

    A and A
    A and A
    B and A
    B and A
    B and A
    B and A
    B and A
    B and A
    B and A
    B and A
    分割线**************************************
    A and A
    A and A
    A and D
    B and A
    B and A
    A and D
    B and B
    B and B
    A and D
    B and B
    B and B
    A and D

    为了方便理解,我列了下每个类的method table

    A
    show(D) -> A.show(D)
    show(A) -> A.show(A)
    
    B,C, D
    show(D) -> A.show(D)
    show(B) -> B.show(B)
    show(A) -> B.show(A)
  • 相关阅读:
    球品与技品
    vi常用操作
    Web功能性测试
    How do I add multiple arguments to my custom template filter in a django template? Stack Overflow
    org.springframework.beans.factory
    » 遍历JavaScript对象的所有属性 [Java堂]
    20.6. urllib2 — extensible library for opening URLs — Python v2.7.3 documentation
    几个电子书网站
    Multiple arguments in Django template filters
    Python抓取网页的性能问题
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4536543.html
Copyright © 2020-2023  润新知