One class cannot access the private members of another class even in Parent-Child relation.
class First
{
static private int x=10;
}
class Second extends First
{
public static void main(String[] args)
{
System.out.println("First - x : " + First.x); // Error : private access
}
}
Outer class can access the private functionality of inner class.
class Outer
{
class Inner
{
private void fun()
{
System.out.println("Inner class private fun...");
}
}
public static void main(String args[])
{
System.out.println("Outer class main");
new Outer().new Inner().fun();
}
}
Inner class access private members of outer class as well.
class Outer
{
private static int x=10;
class Inner
{
private void fun()
{
System.out.println("Outer - x value : " + Outer.x);
}
}
public static void main(String args[])
{
new Outer().new Inner().fun();
}
}
Non-static members of outer class including private, can be accessed from the inner class as follows:
<Outer_class_name>.this.<Outer_class_non-static-member>
class Outer
{
private int x ;
Outer(int x)
{
this.x = x ;
}
class Inner
{
int x ;
Inner(int x)
{
this.x = x ;
}
private void method()
{
System.out.println("Outer's x val : "+Outer.this.x);
System.out.println("Inner's x val : "+this.x);
}
}
public static void main(String args[ ])
{
Outer obj1 = new Outer(100);
Outer.Inner obj2 = obj1.new Inner(200);
obj2.method();
}
}