1. 程式人生 > >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
  }
} ///:~