Forum Stats

  • 3,838,561 Users
  • 2,262,383 Discussions
  • 7,900,687 Comments

Discussions

Accessing private variable of Inner class from Outer class

SASWATA MANDAL
SASWATA MANDAL Member Posts: 5 Red Ribbon

Hi Experts ,

Private members of a class cannot be accessed from outside of that class. Then how in the below code class Outer can access inner.z , z is a private member of the class Inner ? :-

package chapter7; 

class Outer    
{
 int outer_x=100;

 void test()
 {
  Inner inner=new Inner();
  inner.display();
  //System.out.println("y : "+y);       //errors , because Outer has no access to the Inner class variables.
  //System.out.println("y : "+Inner.y); //errors , because Outer has no access to the Inner class variables.
  System.out.println("y : "+inner.y);  
  System.out.println("z : "+inner.z);  // z is a private instance variable of Inner class.
 } 
 
 class Inner     //class Inner is known only within the scope of Outer.
 {
  int y=10;
  private int z=12;
  void display() //the Inner class has direct access to all the variables of the Outer class,but not the reverse.
  {
   System.out.println("display : outer_x= "+outer_x);
  }
 }
 
}

class InnerClassDemo
{
 public static void main(String args[])
 {
  Outer outer=new Outer();
  outer.test();
 }
}

/* OUTPUT

display : outer_x= 100
y : 10
z : 12

*/