Because its Parent's display() method that gets called, and it refers to variable x. Member variables are not runtime polymorphic. In other words, it is determined at compile time, by the type of the reference, which class's variable will be used.
The output of the program is correct. If you move the display() into Child's class, the output will be 100. The reason is when the Child's class instance is created it inherits both x-- from the Child Class and from the Parent class. That being said, since display() method is in the Parent class, it will access the x-- the one which is present in the Parent class--not from the Child's class.
With regards to data hiding(encapsulation), the concept is related to access modifiers--public, protected, default, private. In other words, if you assign a "private" access modifier to "int x", then the 'x' can not be accessed from any other class. Here one point is notable: when a class inherits any other class, the inherited class gets all the behaviors and properties of its parent class.
Joined: Feb 24, 2012
but when we compile it and again decompile using any decompiler we see that in the display function the variable is printed using "this.x". So when the display function is called on child class object it must pass the reference of child class to the function display which is received in "this" variable. then it must have printed the x defined in child class. but it does not. why?
itsHarsh sharma wrote:it must pass the reference of child class to the function display which is received in "this" variable. then it must have printed the x defined in child class. but it does not. why?
Stating that it "must" do something that it clearly does not do is not a productive path to understanding. Since you can see that it clearly doesn't behave as you thought it did, you need to re-examine your assumptions to find out where they went wrong.