Accessing Private Members In Inheritance

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Accessing Private Members In Inheritance

Post 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?

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Accessing Private Members In Inheritance

Post by admin »

Where did you read that? Please post a link so that the context can be understood.
If you like our products and services, please help us by posting your review here.

Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Re: Accessing Private Members In Inheritance

Post by Sweetpin2 »

Hi,

The link is

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

Please check "Private Members in a Superclass" section

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Accessing Private Members In Inheritance

Post 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();
    }
}
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 221 guests