Parent member function hiding child data

I have 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 is 10. This means that at runtime, the parent member function does not use a child data element with the same name (data hiding). What I know is that whenever we extend the class, its member function member of the parent class and data members are available for the Child class, then when I say c.show()why it takes the data member of the Parent class and not the Child class . In addition, I want to know that when we create an object of the Child class, its members of the parent class class are placed in the parent section of the Child class object in Heap, but what happens to the member functions?

+5
source share
3

, . " " . , ( x private). , , :

class Parent{
    private int x=10;

    public int getX() {
        return x;
    }

    void show(){
        System.out.println(this.getX());
    }
}

class Child extends Parent{
    int x=20;

    @Override
    public int getX() {
        return x;
    }

    public static void main(String[] args){
        Child c=new Child();
        c.show();
    }
}

getX(), x .

, :

, , , -- Child

. () . , "" .

, , Child, Child , -?

- . , JVM . , Permanent Generation, , JVM. .

, , , ( , ).

+4

, , , , , - Child, , c.show(), Parent .

. . - - . show() Parent, . x , .

x

+5

X , . , , . .

+1

All Articles