The below code generates no compilation error in eclipse but throws error during Runtime.

public class Animal
{
  public void eat(){}
}
public class Dog extends Animal
{
  public void eat(){}
  public void main(String[] args)
  {
    Animal animal=new Animal();
    Dog dog=(Dog) animal;
  }
}

Output

Exception in thread "main" java.lang.ClassCastException: com.mugil.wild.Animal cannot be cast to com.mugil.wild.Dog
	at com.mugil.wild.Dog.main(Dog.java:12)

By using a cast you’re essentially telling the compiler “trust me. I’m a professional, I know what I’m doing and I know that although you can’t guarantee it, I’m telling you that this animal variable is definitely going to be a dog

Because you’re essentially just stopping the compiler from complaining, every time you cast it’s important to check that you won’t cause a ClassCastException by using instanceof in an if statement.

Generally, downcasting is not a good idea. You should avoid it. If you use it, you better include a check:

Animal animal = new Dog();

if (animal instanceof Dog)
{
Dog dog = (Dog) animal;
}

Leave a reply