• java 向下转型


    向下转型参照下面两示例,编译错误IDE会报错

    package object;
    import java.lang.*;
    import java.util.*;
    class Cycle{
        public int ride(Cycle i) 
        {
            return i.wheel();
        }
        public int wheel()
        {
            return 0;
        }
    }
    
    class Uncicycle extends Cycle{
        public int wheel()
        {
            return 1;
        }
        public void balance(){System.out.println("Tricycle");}
    }
    class Bicycle extends Cycle{
        public int wheel()
        {
            return 2;
        }
        public void balance(){System.out.println("Bicylcle");}
    }
    class  Tricycle extends Cycle
    {
        public int wheel()
        {
            return 3;
        }
       
    }
    
    public class CycleTest extends Cycle{
        public  int ride(Cycle c)
        {
            return c.wheel();
        }
        public static void main(String[] args)
        {
            Cycle[] cy= {
                    new Uncicycle(),
                    new Bicycle(),
                    new Tricycle(),
            };
            
            //((Uncicycle)cy1).balance();
            ((Uncicycle)cy[0]).balance();
            ((Bicycle)cy[1]).balance();
            ((Uncicycle)cy[2]).balance();//Exception in thread "main" java.lang.ClassCastException: object.Tricycle cannot be cast to object.Uncicycle
                                         //  at object.CycleTest.main(CycleTest.java:54)
        }
    }
    package object;
    //: polymorphism/RTTI.java
    // Downcasting & Runtime type information (RTTI).
    // {ThrowsException}
    
    class Useful {
      public void f() {}
      public void g() {}
    }
    
    class MoreUseful extends Useful {
      public void f() {}
      public void g() {}
      public void u() {}
      public void v() {}
      public void w() {}
    }    
    
    public class RTTI {
      public static void main(String[] args) {
        Useful[] x = {
          new Useful(),
          new MoreUseful()
        };
        x[0].f();
        x[1].g();
        // Compile time: method not found in Useful:
        //! x[1].u();
        ((MoreUseful)x[1]).u(); // Downcast/RTTI
        ((MoreUseful)x[0]).u(); // Exception thrown
      }
    } ///:~
  • 相关阅读:
    t
    0409笔记
    vue typescript ui库
    0329
    express+sequelize 做后台
    android申请多个权限的正确姿势
    [BBS] Reply.jsp 03
    [BBS] ShowArticleDetail.jsp 02
    [BBS] ShowArticleTree.jsp 01 帖子的树形展现-递归 、Session 存 login 否
    [Jweb] MyEclipse 的常见操作
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10203257.html
Copyright © 2020-2023  润新知