zoukankan      html  css  js  c++  java
  • java 多态缺陷

    一,会覆盖私有方法

    
    

    package object;

    
    

    class Derive extends Polymorphism{
    public void f1()
    {
    System.out.println("I am Derive");
    }


    }
    public class Polymorphism{
    private void f1()
    {
    System.out.println("I am Polymorphism");
    }
    public static void main(String[] args)
    {
    Polymorphism d = new Derive();
    d.f1();
    }

    
    

    }/* output:
    I am Polymorphism
    *///:~

     

    二.域与静态方法,一旦你访问某个域,这个访问就将在编译期进行解析,这种情况通常不会发生,因为通常将域设为private,只能通过方法访问域

    package object;
    
    class Base{
        public int i = 0;
        public int get(){return i;}
    }
    class Base2 extends Base{
        public int i =2;
        public int get(){return i;}
        public int get1(){return super.i;}
    }
    
    public class Polymorphism{
        public static void main(String[] args)
        {
            Base b1 = new Base2(); //当Base2转型为Base时任何域访问操作都将由编译器解析,因此不是多态的
    //
    ,在本例中,Base2.get()和Base1.get分配了不同的存储空间
    System.out.println(b1.get()+" " + b1.i); Base2 b2 = new Base2(); System.out.println(b2.get()+" " + b2.i + " "+ b2.get1()); } }/* output: 2 0 2 2 0 */

     当某个方法时静态的,它的行为就不具有多态性

    package object;
    
    class Base{
        public static int i = 0;
        public static  String get(){return " " + i;}
    }
    class Base2 extends Base{
        public static int i =2;
        public  static String get(){return " " + i;}
        public int get1(){return super.i;}
    }
    
    public class Polymorphism{
        public static void main(String[] args)
        {
            Base b1 = new Base2();
            Base.get();
             System.out.println(b1.get());
            Base2 b2 = new Base2();
            System.out.println(b2.get());
        }
    }/* output:
     0
     2
    */
  • 相关阅读:
    24-反转链表
    23-链表中环的入口节点
    22-链表中倒数第k个节点
    21-调整数组顺序使奇数位于偶数前面
    18-删除链表的节点
    17-打印从1到最大的n位数
    16-数值的整数次方
    15-二进制中1的个数
    14-剪绳子
    13-机器人的运动范围
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10201123.html
Copyright © 2011-2022 走看看