Java 中的向下转型 [英] Downcasting in Java

查看:23
本文介绍了Java 中的向下转型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中允许向上转换,但是向下转换会导致编译错误.

Upcasting is allowed in Java, however downcasting gives a compile error.

可以通过添加强制转换来消除编译错误,但无论如何都会在运行时中断.

The compile error can be removed by adding a cast but would anyway break at the runtime.

在这种情况下,如果不能在运行时执行,为什么Java允许向下转换?
这个概念有什么实际用途吗?

In this case why Java allows downcasting if it cannot be executed at the runtime?
Is there any practical use for this concept?

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");
  }
}

推荐答案

当有可能在运行时成功时,允许向下转换:

Downcasting is allowed when there is a possibility that it succeeds at run time:

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

在某些情况下这不会成功:

In some cases this will not succeed:

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

当转换(例如最后一个)在运行时失败时,ClassCastException 将被抛出.

When a cast (such as this last one) fails at runtime a ClassCastException will be thrown.

在其他情况下它会起作用:

In other cases it will work:

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

请注意,某些强制转换在编译时是不允许的,因为它们根本不会成功:

Note that some casts will be disallowed at compile time, because they will never succeed at all:

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

这篇关于Java 中的向下转型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆