简体   繁体   English

ClassCastException异常

[英]ClassCastException

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无法转换为B

This happens because the compile-time expression type of new A() is A - which could be 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. 但是,在执行时,引用仅仅是A的实例 - 因此它无法进行转换。 An instance of just A isn't an instance of B . 只是A的实例不是 B的实例。 The cast only works if the reference really does refer to an instance of B or a subclass. 只有在引用确实引用了B或子类的实例时,该转换才有效。

B extends A and therefore B can be cast as A. However the reverse is not true. B扩展A,因此B可以转换为A.但反之则不然。 An instance of A cannot be cast as B. 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没有“ 鸭子打字 ”。

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不允许显式转换。

Once you create the object of a child class you cannot typecast it into a superClass. 一旦创建了子类的对象,就无法将其类型转换为superClass。 Just look into the below examples 请看下面的例子

Assumptions: Dog is the child class which inherits from Animal(SuperClass) 假设: Dog是继承自Animal(SuperClass)的子类

Normal Typecast: 正常的Typecast:

Dog dog = new Dog();
Animal animal = (Animal) dog;  //works

Wrong Typecast: 错误的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 编译器会在运行时检查实际验证内容的语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM