I’ve a code:
class Parent{
int x=10;
void show(){
System.out.println(x);
}
}
class Child extends Parent{
int x=20;
public static void main(String[] args){
Child c=new Child();
c.show();
}
}
Here when I run this program the output comes is 10. Which means at runtime Parent member-function not using the Child data-member with same name(data hiding). The thing I know is that whenever we are extending a class its parent class member-function and data-members are available to Child class, then when I say c.show() why it takes the data-member of Parent class not Child class. Also, I want to know that when we create an object of Child class its Parent class data-members are put in the Parent section of Child class object in Heap, but what happens to member-functions?
The child can’t hide a field from a method in the parent class by simply declaring its own version of the field. You are applying the idea of “data hiding” in reverse. The child can never hide fields from the parent, but the parent can hide fields from the child (by declaring
xasprivate). If you wanted to, you could use encapsulation to achieve your desired effect, like:By overriding the
getX()accessor method, the child can hide the parent’s value ofxfrom the rest of the world.Some other points worth discussing:
This is not entirely correct. Private methods and data members will not be (directly) available to the child class. Only public, protected, and “package-level” methods and fields will be directly accessible to the child class.
Member functions aren’t created per-instance. It would be terribly inefficient if the JVM worked like that. Instead, the method implementations for a given class are defined only once, as part of the
Permanent Generationwhich holds things like class definitions and other internal JVM state. All instances of a given class will share the same method definitions.In the case of a child class, it will share the method definitions of its parent, and it will also have its own definitions added for any methods that exist just in the child (and for any methods that it overrides).