为了账号安全,请及时绑定邮箱和手机立即绑定

Java下播

Java下播

aluckdog 2019-06-21 15:01:51
Java中允许升级,但是下播会导致编译错误。编译错误可以通过添加强制转换来删除,但无论如何在运行时会中断。在这种情况下,如果不能在运行时执行Java为什么允许下播?这个概念有什么实际用途吗?public class demo {   public static void main(String a[]) {       B b = (B) new A(); // compiles with the cast,                           // but runtime exception - java.lang.ClassCastException   }}class A {   public void draw() {     System.out.println("1");   }   public void draw1() {     System.out.println("2");   }}class B extends A {   public void draw() {     System.out.println("3");   }   public void draw2() {     System.out.println("4");   }}Java下播
查看完整描述

3 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

如果有可能在运行时成功,则允许下行广播:

Object o = getSomeObject(),String s = (String) o; // this is allowed because o could reference a String

在某些情况下,这种做法不会成功:

Object o = new Object();String s = (String) o; // this will fail at runtime, because o doesn't reference a String

在其他情况下,它将发挥作用:

Object o = "a String";String s = (String) o; // this will work, since o references a String

当强制转换(例如最后一次)在运行时失败时,ClassCastException会被扔出去。

请注意,某些强制转换在编译时将被禁止,因为它们永远不会成功:

Integer i = getSomeInteger();String s = (String) i; // the compiler will not allow this, since i can never reference a String.


查看完整回答
反对 回复 2019-06-21
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

使用您的例子,您可以:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();}


查看完整回答
反对 回复 2019-06-21
  • 3 回答
  • 0 关注
  • 358 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号