zoukankan      html  css  js  c++  java
  • 多态之美

      多态是Java面向对象的三大特性(封装,继承,多态)之一,多态的主要目的是对不同对象的不同实现,继承,是子类对父类方法等的沿用(避免重复造轮子)。

      多态的必要条件:继承(父类中最好要有父类的对象接口)、父类指向子类、重写(无重写无多态)

           代码演示:                                           

     public class Test6 {

    static class A {

      public String show(D obj){
        return ("A and D");
    }


    public String show(A obj){
      return ("A and A");
    }

    }


    static class B extends A{
      public String show(B obj){
        return ("B and B");
    }


    public String show(A obj){
      return ("B and A");
    }

    }
    static class C extends B{}
    static 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(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));
      }

    ===================================================================

    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

    答案对了没?

    总结一下:

    多态:父类指向子类,先从父类寻找,父类中没有找到本类,就在父类寻找本类的父类借口,寻找到后观察子类是否重写过,如果重写按照重写的结果否则按照父类的结果;
    有继承关系的类:先从本类寻找,如果找不到,找父类,父类找不到在从本类中寻找父类,找不到,找父类,依次类推(寻找按照类本身去寻找,本身类找不到按找最近父类)
    没有继承的类:先从本类找,如果找不到,在寻找父类

    继承和多态的关系:

    继承,在调用接口时,先从被创建的对象中寻找本类,如果找不到,在从父类中寻找,如果父类中也不存在,
    呢就从创建的对象中寻找父类然后在从父类中寻找,依次类推;

    多态是强制从父类中寻找,寻找不到在父类中寻找有继承关系的父类,即使创建的对象中存在本类,也不会去寻找。

  • 相关阅读:
    axios 配置
    vue 配置App.js
    vue 挂载方式
    常用的js
    vuex
    vue搭建环境
    JS中 toString() & valueOf()
    html-webpack-plugin 中使用 title选项设置模版中的值无效
    webpack为什么加载不了css?
    visual studio for mac 安装文件
  • 原文地址:https://www.cnblogs.com/fjl0418/p/11729185.html
Copyright © 2011-2022 走看看