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类中没有这个方法

  • 相关阅读:
    Webix快速跨浏览器的JavaScript UI组件
    [转]UltraISO制作U盘启动盘安装Win7/9/10系统攻略
    JavaScript中setTimeout()和setInterval()的区别
    AngularJS中文介绍
    Android Studio参考在线文章
    Android原型界面设计工具
    B-JUI(Best jQuery UI) 前端框架
    Linux Ubuntu download
    Jquery之家5个顶级Material Design框架
    bootstrap绿色大气后台模板下载[转]
  • 原文地址:https://www.cnblogs.com/AndersonX/p/8330938.html
Copyright © 2011-2022 走看看