zoukankan      html  css  js  c++  java
  • 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
      }
    } ///:~
  • 相关阅读:
    dup和dup2
    cassandra nodetools
    python 之mechanize
    IDEA使用GsonFormat
    游标应用
    SQL 2005 with(nolock)详解
    SET NOCOUNT ON
    异常处理机制(Begin try Begin Catch)
    FILLFACTOR 作用 sql
    触发器语法
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10203257.html
Copyright © 2011-2022 走看看