小编典典

Downcasting in Java

java

Java中允许进行向上转换,但是向下转换会产生编译错误。

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

在这种情况下,如果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");
  }
}

阅读 449

收藏
2020-02-28

共1个答案

小编典典

当可能在运行时成功进行向下转换时:

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将抛出a。

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

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.
2020-02-28