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

  • 相关阅读:
    AVFrame 解析
    Mat与图像的基本概念
    linux基本操作
    Makefile 使用
    MySQL的安装与配置——详细过程
    k8s imagePullPolicy拉取策略
    K8S拉取Django项目创建pod
    Harbor单点仓库部署
    Django项目构建发布Harbor仓库
    K8S集群部署-二进制部署
  • 原文地址:https://www.cnblogs.com/AndersonX/p/8330938.html
Copyright © 2011-2022 走看看