Inheritence | Downcasting and Upcasting

Just because you’re an Animal doesn’t mean you’re a Cat. You could be a Dog. That’s why it’s illegal to cast an Animal into a Cat.

On the other hand, is every Cat an Animal? The answer is “yes”. That’s why you could write code like this:

Animal animal = new Cat();

or

Cat cat = new Cat();
Animal animal = cat;

Also what’s worth noting is you can do this:

Animal animal = new Cat();
Cat cat = (Cat) animal;

The reason you can do this is that your animal variable is actually referencing a Cat instance. Therefore you’re allowed to cast it back into a variable that references a Cat.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s