Polymorphism + Upcasting: Which method implementation will be used? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Polymorphism + Upcasting: Which method implementation will be used?

I'm going back over the Java course to review everything I've learned, but even though I've finished the course already, the Polymorphism lesson is bothering me. You see, in the example provided, there are two objects, Dog and Cat, that extend the Animal class. One Dog object called a and one Cat object called b are instantiated, but they are upcasted to type Animal! Wouldn't this mean that a.makeSound() and b.makeSound would both call the makeSound() method in Animal, NOT Dog and Cat since both a and b have been upcasted? Could someone please explain to me why this isn't so in the example? What am I missing?

14th Feb 2017, 12:41 AM
Delaina Hardwick
Delaina Hardwick - avatar
1 Answer
+ 3
Just to clear up things. You can never change the actual object when upcasting , the only thing that chages is the reference variable, lets take the example below: class Animal{ public void doSomething(){ //TODO } } class Dog inherits Animal{ public void doSomething(){//overriding //TODO } } class Cat inherits Animal{ public void doSomething(){//overriding //TODO } } the variable "c" below is of type animal which means it can refer to any object which inherits from Animal (this is known as polymorphism, object which can take many forms), however as you can see below "c" is actually a cat hence the reference type doesnt always determine what the reference variable points to. Animal c = new Cat(); //upcasting c.doSomething(); // calls the cat because "c" is a cat object . We used the Animal as a type so that the variable "c" can take on many forms as in it can refer to more than one objects as long as those objects inherit from animal the below would fail because even though the reference "c" is of type animal the actialy object it refers to is a cat object. Dog d = (Dog)c; // downcasting "c" to dog The below would pass because "c" refers to a cat object. Cat cat = (Cat)c; // downcasting "c" to cat Finally, always use "instanceof" method before casting types, just to ensure its the correct type.
14th Feb 2017, 1:14 AM
Ousmane Diaw