Wednesday, 27 January 2016

Explicit casting from super class to subclass : Downcasting

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;

The assignment Dog dog = (Dog) animal; at runtime it generates a ClassCastException.

By using a cast you're essentially telling the compiler "trust me that this animal variable is definitely going to be a dog."

Since the animal isn't actually a dog (may be Cat).

The VM throws an exception at runtime because you've violated that trust.

The compiler is a bit smarter than just blindly accepting everything, if you try and cast objects in different inheritance hierarchies then the compiler will throw it back at you because it knows that could never possibly work.

By using instanceof operator, we can avoid the ClassCastException.

It's an animal, you could do Animal animal = new Dog(); and it'd be a dog.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...