首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java中的向下转换

Java中的向下转换
EN

Stack Overflow用户
提问于 2008-12-19 12:11:44
回答 7查看 231.2K关注 0票数 196

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

回答 7

Stack Overflow用户

回答已采纳

发布于 2008-12-19 12:20:14

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

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.
票数 320
EN

Stack Overflow用户

发布于 2008-12-19 13:08:04

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

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();
}
票数 18
EN

Stack Overflow用户

发布于 2010-03-16 19:25:49

@ Original Poster -查看内联评论。

public class demo 
{
    public static void main(String a[]) 
    {
        B b = (B) new A(); // compiles with the cast, but runtime exception - java.lang.ClassCastException 
        //- A subclass variable cannot hold a reference to a superclass  variable. so, the above statement will not work.

        //For downcast, what you need is a superclass ref containing a subclass object.
        A superClassRef = new B();//just for the sake of illustration
        B subClassRef = (B)superClassRef; // Valid downcast. 
    }
}

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");
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/380813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档