Java 中的 Downcasting

2022-08-31 06:19:14

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

答案 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

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

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.

答案 2

使用您的示例,您可以执行以下操作:

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

推荐