• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Justify the output of the code (inheritance/overriding problem)

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello ranchers,

Can anyone justify the output of following code ?



According to myself output should be as follow :-

Parent's method2()
Child's method1()

Because, we are calling method2 with reference of child class.

But, the actual output is :-


Parent's method2()
Parent's method1()

Please, explain it.

Thanking you all,

Pranav Thakker
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Output

Parent's method2()
Parent's method1()

is absolutely correct.

method1 cannot be invoked in polymorphic way because you do not override it. As long as it is marked private it cannot be inherited.
If you would change it to public your output will be as you thought.
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
private method,method1() in parent class is not overridden by child class.it is another method with the same name
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If u change the method1() in parents class like:

then the output would be
Parents method2()
Child method1()


Thanks
Balaji.S
 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


But, the actual output is :-
Parent's method2()
Parent's method1()



It's a Child object and a Child declaration, so how is it possible that the output above has "Parent's method1()"?!!
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Search JavaRanch and you can find more posts about this.
Here is one.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic