在Java中向下转换 [英] Downcasting in Java

查看:114
本文介绍了在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 suceeds at run time:

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

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

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

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

请注意,一些cast将在编译时被禁止,因为它们永远不会成功:

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天全站免登陆