• Post Reply Bookmark Topic Watch Topic
  • New Topic

Upcasting and polymorphism  RSS feed

 
Richard Attix
Greenhorn
Posts: 10
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi folks!  Thanks ahead of time for your help!

I was going over the concept of polymorphism, and came across this code as an explanation:


OK so I understand everything all the way down to "Animal a = new Dog();"   Why not write Dog a = new Dog(); ?    My understanding is that when you upcast as we are doing in the first case to the Animal Object where the sound is Grr.., we will be losing access to any properties or methods in the Dog and Cat classes.  So when this code is run, why does the dog make the "woof" sound and the cat make the "meow" sound when they should both be making the "Grrr" sound because we have upcast those two objects (dog and cat) to Animal and lost those individual sounds?  What am I missing??  Thanks for helping out!!!
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Richard Attix wrote:. . . when you upcast as we are doing in the first case to the Animal Object where the sound is Grr.., we will be losing access to any properties or methods in the Dog and Cat classes.  . . .
You lose access to any new methods in the subclasses. You are not casting anything. You are declaring an Animal, which might be a bird, a cat or a dog.
Instance methods can be polymorphic, but other things can't be.
So you declare it as an Animal, which has a makeSound() method. It doesn't have a flyIntoTree() method, which a Bird would have. It doesn't have a climbIntoTree() method like a Cat, nor an xxxToTree() method like a Dog. But all Animals can makeSound(), so that is the method you can call on an Animal reference. The polymorphic bit, which applies to most instance methods and nothing else, is that at runtime the JVM (not the compiler) looks for the method to execute. It finds it in the corresponding Class object, and if it is a Dog, that goes woof, or a cat would go meow or a bird tweet. It only looks in the Animal class object if it can't find such a method in its own Class object (=the method hasn't been overridden).
Find the w‍ord polymorphism and click on it, because it turns into a link which may help you about polymorphism.

Remind yourself how code tags work; I have corrected them for you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!