java - Java 中的向下转型

标签 java casting

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

最佳答案

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

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

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

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

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

请注意,某些类型转换在编译时将被禁止,因为它们根本不会成功:

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

关于java - Java 中的向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569578/

相关文章:

go - Go 中的类型转换结构是无操作的吗?

转换要在 strcat 中使用的整数

java - JList如何重绘?

java - hibernate 代码中的 session.connection() 类型未定义

java - Gradle 3.0.0 的 Android 插件 : Could not find com. google.http-client :google-http-client-parent:1. 24.1

java - 为什么我们不能从 Object[] 转换为 String[],而我们可以从数组中的值转换?

java.lang.ClassCastException : java. lang.Float 无法转换为 java.lang.String

java - 使用 JRuby 或 Python 调用一些第三方 Java 库 - 架构问题

java - 使用 Java 中的 Scanner 类读取文本文件的特定部分

c++ - 为什么这个 reinterpret_cast 不编译?