Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
  • Tim Holloway
  • Carey Brown
  • salvin francis

Unexpected result through same method called differently

Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am posting this for my accountability buddy at work, with whom I am trying to keep motivated to get through my OCA certification.
The following code has interesting output:

Why does the number of feet change for the last WildAnimal object named wildAnimalAndTiger? I can understand that the object is a WildAnimal, however, that would mean both the results would be 4?
Although I am not surprised by this result and "feel" like this answer makes sense somewhere, I cannot explain it fully why it is so. Does it have to do with the way getAmountOfFeet() is called? Is there a difference when it is done through the object directly, and when it is done through another method inside the same object?

It is probably out of scope for the OCA exam, but we are still very curious to get the full answer on this
Posts: 65474
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to a more general forum where you will probably get more attention.

It is polymorphism at work. When you have two instance methods with the same name and parameter types in a superclass and a subclass, the subclass' method is said to override the superclass' method. That doesn't apply to static methods. in the case of line 5, the runtime type of the object is Tiger, not wild animal. That is how polymorphism works. The Tiger version of the instance method is called, and that calls the static method from the same class (8 feet).
This shows how much confusion you can get if you declare static methods with the same name in superclass and subclass; they don't override each other but hide each other: see this FAQ.
Posts: 2348
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the correct way of writing your code:

Hope this clarifies your doubt. One should not use objects to refer to static content, it will cause confusion as shown in your case.
Hug your destiny! And hug this tiny ad:
Enterprise-grade Excel API for Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!