i have two classes in java as:
class A {
int a=10;
public void sayhello() {
System.out.println(\"class A\");
}
}
class B extends A {
int a=20;
pub
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)
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:
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