• 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
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
  • Carey Brown
  • salvin francis
  • Claude Moore

Private method overiding  RSS feed

Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

OCAJP - 1 book assessment test has below program. I did not understand how could parent access its private method when parent reference instantiated child object.

ouput is deer childCH false.

I am expecting deer childCH true. According to run-time polymorphism, child class hasHorns has to be invoked, right? Please let me know. Thanks.
Posts: 23830
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Private methods are not overridden -- no polymorphism.

Posts: 64100
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please supply more details of the book: is it by Boyarsky and Selikoff?

Please follow the execution through the constructors;-
  • 1: ChildCH constructor calls no‑arguments superclass constructor.
  • 2: ConstructorHierarchy constructor calls its superclass' constructor (=Object()).
  • 3: Object() completes and control passes back to ConstructorHierarchy() which prints “deer”
  • 4: ConstructorHierarchy() ocmpletes and control passes to ChildCH() which prints “ChildCH”
  • 5: Line 21 completes.
  • Now,, you can access the private method because you are inside the same class. The hasHorns() method is not inherited by ChildCH; it exists only in ConstructorHierarchy. Since there is no polymorphism involved, the type of the method is bound statically at compile‑time on the declared type of the variable, i.e. ConstructorHierarchy. The method with a similar name in the subclass is not an overriding method.

    Private methods are not inherited. The method in the subclass is a new method completely unrelated to the superclass' method. So it is not called polymorphicaally and the superclass method prints false.
    Well behaved women rarely make history - Eleanor Roosevelt. tiny ad:
    Create Edit Print & Convert PDF Using Free API with Java
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!