美文网首页
Downcasting

Downcasting

作者: Icatream | 来源:发表于2016-11-14 14:50 被阅读0次

Class A父类

public class A {
public void test(){
    System.out.println("Hi");
  }
}

Class B子类

public class B extends A {
    public void test(){
        System.out.println("Bye");
    }
}

进行downcasting,eclipse未出现警告

A a = new A();
((B)a).test();

运行结果报错

Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
    at B.main(B.java:25)

到底能不能进行downcasting?
不能向下转换。
父类中可能含有其他子类,例如猫不能转换成狗。

相关文章

网友评论

      本文标题:Downcasting

      本文链接:https://www.haomeiwen.com/subject/ggphpttx.html