zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    8.2.8 A Simple Game
    8.2.7 Be the Winner
    8.2.6 John
    8.2.5 kiki's game
    8.2.2 Good Luck in CET-4 Everybody!
    8.2.4 悼念512汶川大地震遇难同胞——选拔志愿者
    8.1.8 Team Queue
    8.2.1 Brave Game
    8.1.7 愚人节的礼物
    8.1.6 Windows Message Queue
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4536543.html
Copyright © 2011-2022 走看看