码迷,mamicode.com
首页 > 编程语言 > 详细

java 向下转型

时间:2018-12-31 21:54:18      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:pil   ast   ann   amp   UNC   phi   turn   错误   extend   

向下转型参照下面两示例,编译错误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
  }
} ///:~

 

java 向下转型

标签:pil   ast   ann   amp   UNC   phi   turn   错误   extend   

原文地址:https://www.cnblogs.com/jiangfeilong/p/10203257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!