• (七)《Java编程思想》——多态的缺陷


    1.不能“覆盖”私有方法

    package chapter8;
    
    /**
     * 不能"覆盖"私有方法
     */
    public class PrivateOverride {
        private void f() {
            System.out.println("private f()");
        }
    
        public static void main(String[] args) {
            PrivateOverride po=new Derived();
            po.f();
            Derived d=new Derived();
            d.f();
        }
    }
    
    class Derived extends PrivateOverride {
        public void f() {
            System.out.println("public f()");
        }
    }

    【运行结果】:
    private f()
    public f()

    2.域不呈多态性(只有普通方法具有多态)

    /**
     * 
     */
    package chapter8;
    
    /**
     * 缺陷:域与静态方法
     */
    class Super {
        public int field = 0;
    
        public int getField() {
            return field;
        }
    }
    
    class Sub extends Super {
        public int field = 1;
    
        public int getField() {
            return field;
        }
    
        public int getSuperField() {
            return super.field;
        }
    }
    
    public class FieldAccess {
        public static void main(String[] args) {
            Super sup = new Sub();
            System.out.println("sup.field = " + sup.field + " sup.getField() = "
                    + sup.getField());
            Sub sub = new Sub();
            System.out.println("sub.field = " + sub.field + " sub.getField() = "
                    + sub.getField() + " sub.getSuperField = "
                    + sub.getSuperField());
        }
    }

    【运行结果】:

    sup.field = 0 sup.getField() = 1
    sub.field = 1 sub.getField() = 1 sub.getSuperField = 0

    3静态方法不呈多态性

    package chapter8;
    
    /**
     * 静态方法不具有多态性
     */
    class StaticSuper {
        public static String StaticGet() {
            return "Base staticGet()";
        }
    
        public String dynamicGet() {
            return "Base dynamicGet()";
        }
    }
    
    class StaticSub extends StaticSuper {
        public static String StaticGet() {
            return "Derived staticGet()";
        }
    
        public String dynamicGet() {
            return "Derived dynamicGet()";
        }
    }
    
    public class StaticPolymorphism {
        public static void main(String[] args) {
            StaticSuper sup = new StaticSub();
            System.out.println(sup.StaticGet());
            System.out.println(sup.dynamicGet());
        }
    }

    【运行结果】:

    Base staticGet()
    Derived dynamicGet()

  • 相关阅读:
    淘宝返回顶部
    混合布局
    css布局使用定位和margin
    选项卡 js操作
    ul li 好友列表
    js添加删除元素
    下拉列表的简单操作
    python笔记
    kali linux 虚拟机网卡未启动
    python 重新安装pip(python2和python3共存以及pip共存)
  • 原文地址:https://www.cnblogs.com/echolxl/p/3209022.html
Copyright © 2020-2023  润新知