ClassCastException

I have two classes in 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 an error, but at runtime it displays an error: An exception in the stream "main" java.lang.ClassCastException: A cannot be added to B

+5
source share
4 answers

This is due to the fact that the type of the compilation time expression new A()is equal A- it can be a reference to an instance B, so casting is allowed.

A - . A B. , B .

+16

B A, B A. . A B.

Javascript, , , Java " duck typing".

+7

:

  A aClass = new B(); 

, :

   B b = (B) aClass;

, . .

+1
source

Once you create an object of a child class, you cannot convert it to a superclass. Just check out the examples below.

Assumptions:             Dog is a child class that inherits from Animal (SuperClass)

Plain Typecast:

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

Invalid Typecast:

Animal animal = new Animal();
Dog dog = (Dog) animal;  //Doesn't work throws class cast exception

Below Typecast really works:

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

The compiler verifies its syntax for the actual runtime.

0
source

All Articles