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

  • 相关阅读:
    rpm 命令详解
    自动配置原理
    ssm框架整合
    单个库创建用户和权限
    Mysql5.7安装过程
    Eclipse和JDK版本以及位数对应关系
    DHCP服务器
    常用Dos命令
    八、Linux上常用网络操作
    数据库分区表(转)
  • 原文地址:https://www.cnblogs.com/AndersonX/p/8330938.html
Copyright © 2011-2022 走看看