1

I have this piece of code

public class Base {
    private int x=10;
     void show(){
         System.out.println(x);
     }

}


public class Child extends Base {

    public static void main(String[] args) {

        Child c1=new Child();
        c1.show();

    }

}

This piece of code is working fine and output is 10.Can anyone please Elaborate how this private data member is access in child class..

1 Answers1

8

It isn't. The show() method is accessed. That method of the parent then accesses the field x. The show() method has default access, which includes access by the Child as it is in the same package.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Are you sure the method invoked is from the parent and not from the child? I don't any thing related to parent in `Child c1=new Child(); c1.show();`. – Bhesh Gurung Oct 27 '12 at 17:25
  • @BheshGurung The `show()` method is part of the parent. It is inherited by the child but it still has all the access rights of the parent. If the child had overridden the parent method it would not have had access anymore. – Maarten Bodewes Oct 27 '12 at 17:29
  • @BheshGurung If you would have access to override show() of course. The default mode [doesn't](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private). – Maarten Bodewes Oct 27 '12 at 20:04