• 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)
  • 相关阅读:
    Java实现 洛谷 P1028 数的计算
    Java实现 洛谷 P1028 数的计算
    Java实现 洛谷 P1028 数的计算
    Nginx+Memcached+Tomcat集群配置(MSM--win7 64bit)
    Tomcat安装、配置、优化及负载均衡详解
    Nginx+Tomcat+Memcached部署
    Nginx+Tomcat+Memcached实现会话保持(MSM)
    Nginx+tomcat配置集群负载均衡
    Nginx+Tomcat搭建高性能负载均衡集群的实现方法
    Nginx+Tomcat的配合使用
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4536543.html
Copyright © 2020-2023  润新知