• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Query regarding Field Hiding

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

Can any one explain, the situation in which Method Overriding and Field Hidding occur at the sametime. Below is the code that depicts the situation.


The Output of the above program is
this is returnI() of B 20
10


I was expecting the result to be
this is returnI() of B 10
10


Can anyone explain the Output.
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instance methods are chosen dynamically at run time based on the type of the actual object on which the method is called. In this case, the actual object is of type B. Your guess that the output would include "this is returnI() of B" shows that you knew that fact. Within the returnI() method in class B, the instance variable i (of class B) is within scope, so the method can return a copy of that variable's value without a problem. From the point of view of that method, i is a variable whose value is 20. The method is able to return a copy of that value.

Note that a.returnI() is not accessing the i instance variable directly. Instead, it is calling the returnI() method of an object of type B. Within that method, i refers to the variable in the same class as the method, which equals 20. So when the method returns the value of i, it returns 20.

As you correctly surmised, the value of a.i is 10, since instance variables accessed directly via the dot operator (.) are selected based on the type of the reference variable, not the type of the actual object. In this case, the reference variable is of type A, so the value of a.i is 10.
 
Water! People swim in water! Even tiny ads swim in water:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic