Page 1 of 1

Accessing Private Members In Inheritance

Posted: Tue Feb 26, 2013 3:00 pm
by Sweetpin2
In Java API it says

"A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass."


Can you please give me an example of this?

Re: Accessing Private Members In Inheritance

Posted: Tue Feb 26, 2013 5:19 pm
by admin
Where did you read that? Please post a link so that the context can be understood.

Re: Accessing Private Members In Inheritance

Posted: Tue Feb 26, 2013 5:40 pm
by Sweetpin2
Hi,

The link is

http://docs.oracle.com/javase/tutorial/ ... asses.html

Please check "Private Members in a Superclass" section

Re: Accessing Private Members In Inheritance

Posted: Tue Feb 26, 2013 5:59 pm
by admin

Code: Select all

package exercise;

class Outer {
  private int x = 10;
  class Inner{
       
      //lets the subclass of Outer have indirect access to Outer's private member x
       public void changeX(int val){
        x = val;    
       }
  }
  
  public void printX(){
           System.out.println(x);
  }

}
class NewOuter extends Outer{
    public void accessPrivate(){
        Inner inner = new Inner();
        //change super class's private member x
        inner.changeX(20);
        printX();
    }
}
public class PrivateTest {
    public static void main(String[] args) {
        NewOuter o = new NewOuter();
        o.accessPrivate();
    }
}