java 类投射异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3092796/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ClassCastException
提问by Kalpesh Jain
i have two classes in java as:
我在java中有两个类:
class A {
 int a=10;
 public void sayhello() {
 System.out.println("class A");
 }
}
class B extends A {
 int a=20;
 public void sayhello() {
 System.out.println("class B");
 }
}
public class HelloWorld {
    public static void main(String[] args) throws IOException {
 B b = (B) new A();
     System.out.println(b.a);
    }
}
at compile time it does not give error, but at runtime it displays an error : Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
在编译时它不会给出错误,但在运行时它会显示一个错误:线程“main”中的异常 java.lang.ClassCastException: A cannot be cast to B
回答by Jon Skeet
This happens because the compile-timeexpression type of new A()is A- which couldbe a reference to an instance of B, so the cast is allowed.
发生这种情况是因为编译时表达式类型new A()是A- 它可能是对 实例的引用B,因此允许强制转换。
At execution time, however, the reference is just to an instance of A- so it fails the cast. An instance of just Aisn'tan instance of B. The cast only works if the reference really does refer to an instance of Bor a subclass.
然而,在执行时,引用只是对 - 的一个实例,A因此它无法进行强制转换。just的实例A不是的实例B。只有当引用确实引用了 的实例B或子类时,强制转换才有效。
回答by dsmith
B extends A and therefore B can be cast as A. However the reverse is not true. An instance of A cannot be cast as B.
B 扩展了 A,因此 B 可以转换为 A。但是反过来就不是这样了。A 的实例不能转换为 B。
If you are coming from the Javascript world you may be expecting this to work, but Java does not have "duck typing".
如果您来自 Javascript 世界,您可能希望它能够工作,但 Java 没有“鸭子输入”。
回答by Ramesh
First do it like this :
首先这样做:
  A aClass = new B(); 
Now do your Explicit casting, it will work:
现在进行显式转换,它将起作用:
   B b = (B) aClass;
That mean's Explicit casting must need implicit casting. elsewise Explicit casting is not allowed.
这意味着显式转换必须需要隐式转换。elsewise 不允许显式转换。
回答by router
Once you create the object of a child class you cannot typecast it into a superClass. Just look into the below examples
一旦创建了子类的对象,就不能将其类型转换为超类。看看下面的例子
Assumptions:Dog is the child class which inherits from Animal(SuperClass)
假设:Dog 是继承自 Animal(SuperClass) 的子类
Normal Typecast:
正常类型转换:
Dog dog = new Dog();
Animal animal = (Animal) dog;  //works
Wrong Typecast:
错误的类型转换:
Animal animal = new Animal();
Dog dog = (Dog) animal;  //Doesn't work throws class cast exception
The below Typecast really works:
下面的 Typecast 确实有效:
Dog dog = new Dog();
Animal animal = (Animal) dog;
dog = (Dog) animal;   //This works
A compiler checks the syntax it's during the run time contents are actually verified
编译器检查它在运行时内容实际验证的语法

