zoukankan      html  css  js  c++  java
  • 多态中的题目分析题

    多态(Polymorphic)概述:事物存在的多种形态

    多态的前提:a.要有继承关系 b.要有方法重写 c.要有父类引用指向子类对象

    多态中的成员访问特点之成员变量:编译看左边(父类),运行看左边(父类)

    多态中的成员访问特点之成员方法:编译看左边(父类),运行看右边(子类) 动态性

    分析多态中的题目:

    =======A程序============

    class Fu {
    public void show() {
    System.out.println("fu show");
    }
    }

    class Zi extends Fu {
    public void show() {
    System.out.println("zi show");
    }

    public void method() {
    System.out.println("zi method");
    }
    }

    class Test1Demo {
    public static void main(String[] args) {
    Fu f = new Zi();
    f.method();
    f.show();
    }
    }

    由于Fu中没有method()方法,由此该程序在编译的时候就出现问题

    =======B程序============


    class A {
    public void show() {
    show2();
    }
    public void show2() {
    System.out.println("我");
    }
    }
    class B extends A {
    public void show2() {
    System.out.println("爱");
    }
    }
    class C extends B {
    public void show() {
    super.show();
    }
    public void show2() {
    System.out.println("你");
    }
    }
    public class Test2DuoTai {
    public static void main(String[] args) {
    A a = new B();
    a.show();

    B b = new C();
    b.show();
    }
    }

    程序的结果:

    爱 你

    分析:

    A a = new B();

    a.show();   编译看B的父类A有show()方法,编译通过 运行看右边 子类没有show()方法 但是子类继承了父类的方法 用父类A 的show()方法,show()方法 调研show2()(子类对show2()重写)结果为 爱

    B b = new C();
    b.show();   编译看左边 父类B由于继承了A 所有有show()方法,编译通过 运行看右边子类show()方法 里面调用super.show2()调用子类的show2() 结果为 你

    转载于:https://www.cnblogs.com/taowangwang/p/9475954.html

  • 相关阅读:
    Google
    LeetCode 664. 奇怪的打印机
    LeetCode 79. 单词搜索
    LeetCode 224. 基本计算器
    Windows 端口映射
    LeetCode 354. 俄罗斯套娃信封问题
    LeetCode 300. 最长递增子序列
    LeetCode 338. 比特位计数
    LeetCode 395. 至少有K个重复的最长子串
    LeetCode 424. 替换后的最长重复字符
  • 原文地址:https://www.cnblogs.com/twodog/p/12136201.html
Copyright © 2011-2022 走看看