zoukankan      html  css  js  c++  java
  • Java的duotaix

    今天看到博客园上一位原创的博文讲解Java多态性,觉得不错,不过没有解释,特此注释,侵删

    public class MyTest {
        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)); 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)); a2.name(); } } class A { public void name(){ System.out.println("My Name is A"); } public String show(D obj){ return ("A and D"); } public String show(A obj){ return ("A and A"); } } class B extends A{ public void name(){ System.out.println("My Name is B"); } 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{}

    结果是

    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
    My Name is B

    这里主要说一下

    A a2 = new B()

    关于向上转型:定义了B类,编译器在编译的时候查找A类里面的方法,但是在运行的时候,JVM去运行B类里面的方法,如果B类中不存在就运行A类的方法。
    也就是说,执行a2.show(b)时,先去A类中查找,找到show(A obj),运行的时候运行B类中的show(A obj);执行a2.show(d)时,只会执行A类中的show(D obj),因为B类中没有这个方法

  • 相关阅读:
    StatusStrip控件的使用(转:http://blog.sina.com.cn/s/blog_4f18c3ec0100fguf.html)
    linux根文件系统
    git使用技巧
    修改git用户名
    luci中添加application
    openwrt安装依赖库
    STM32(二十九)定时器介绍
    openwrt部分文件解析
    uci.js文件解析
    矿机算力
  • 原文地址:https://www.cnblogs.com/AndersonX/p/8330938.html
Copyright © 2011-2022 走看看