Why this code is not working? When i casting, I get ClassCastExeption Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B at HelloWorld.main
public class HelloWorld
{
public static void main(String[] args)
{
B b1 = (B)new A();
b1.a();
}
}
public class A
{
public void a (){
System.out.println("A.a");
}
public void b (){
System.out.println("A.b");
}
}
public class B extends A{
}
Casting can't always be done in both ways.
If you are creating an Animal, by calling "new Animal()", you are creating an Object that is an Animal, but it cannot be downcasted to Dog. Because it's not a dog.
However when you create a Dog by calling "new Dog()", then you can upcast it to "Animal" and downcast it back to "Dog".
Dog dog = new Dog();
Animal animal = dog; //upcasting to Animal
if(animal instanceof Dog){ // testing if the Animal is a Dog
Dog dog2 = (Dog) animal; //downcast
}