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
  }
} ///:~

 

posted @ 2018-12-31 20:46  江期玉  阅读(451)  评论(0编辑  收藏  举报