• 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Understanding inheritance

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

I have started java recently. Got a snippet of a code. can anybody please explain this inheritance?
I have got 2 classes Test1 and Test2. Test1 inherits Test2.



The output is :
20
Executing method of Test1

but when I am replacing Test1 with Test2 The output is :
40
Executing method of Test1

It is showing accessing the instance variable of Test2 class but method of Test1 class why?

Please help. Thank you.

Regards,
Bhaskar
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Bhaskar Mukhejee wrote:

but when I am replacing Test1 with Test2 The output is :
40
Executing method of Test1
Is this what you have done.

Regards,
Bhaskar



So here t refers to Test2 But at runtime the instance is created of Test1 so it overrides the math method of Test1.
 
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Bhaskar Mukhejee wrote:It is showing accessing the instance variable of Test2 class but method of Test1 class why?



It's because variables aren't overridden, only methods are.
 
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This FAQ might help you.
 
Bhaskar Mukhejee
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks to all of you for this help.

Regards,
Bhaskar
 
If you were a tree, what sort of tree would you be? This tiny ad is a poop beast.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic