Can Outer Java Classes Access Inner Class Private Member?

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Java allows us to define a class inside another class called a nested class. A nested class is of two types - static and non-static. The non-static nested class can also be referred to as:

Inner Classes

Nested inner classes have access to the members of the outer class, including the private ones. A nested class can be public, private, package private, or protected as a member of the outer class. The outer java classes can access inner class private or protected members. These access modifiers on the inner classes will only affect their visibility in classes derived from the outer class. Non-static nested class in Java

Example

The outer class can access any member of the inner class indirectly through an object of the inner class.

Output:

Can the Inner Class Access Outer Class Variables in Java?

Inner classes can access the variables of the outer class, including the private instance variables. Unlike the non-static nested classes, the static nested class cannot directly access the instance variables or methods of the outer class. They can access them by referring to an object of a class.

Example

Output:

Conclusion

  • Outer classes can access inner class private members in Java until a non-static member accesses it from a static context or an inaccessible scope.
  • Inner classes can access the variables of the outer class, including the private instance variables.