1

If I have the following situation where I define a class Animal and another class Dog that extends Animal with the following two lines of code:

1) Dog d = (Dog) new Animal(); //explicit downcast

2) Animal a = new Dog(); //automatic upcast

What are the pros and cons of defining two animals this way? Specifically, in what situations would I prefer (1) over (2) and vice versa?

From what I understand, we downcast to have access to Dog's methods, but then why not just call it a dog?

Thanks in advance!

lemonuzzi
  • 21
  • 1
  • 3

1 Answers1

0

It sounds like you're interested in learning more about upcasting and downcasting, in which case you might find this answer to be helpful.

To expand a bit on your questions and pull from the linked answer, upcasting is always allowed, but downcasting involves a type check, which can throw a ClassCastException.

Nevertheless, you could use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent these exceptions like the in code below.

One reason why you may choose to downcast is because you want a method to work for all animals, but have it do something in particular for a Dog, which can lead to code like this:

public void pet(Animal animal) {

    // Do something else if animal is a Dog
    if (animal instanceof Dog) {
        Dog dog = (Dog) animal;
        dog.growl();
    }
}
AbsoluteSpace
  • 710
  • 2
  • 11
  • 21