Home >Java >javaTutorial >Why Can Outer Java Classes Access Inner Class Private Members?
Question:
Why can outer Java classes access inner class private members? The following code snippet demonstrates this behavior:
class ABC { class XYZ { private int x = 10; } public static void main(String... args) { ABC.XYZ xx = new ABC().new XYZ(); System.out.println("Hello :: " + xx.x); // Why is this allowed? } }
Answer:
Nested classes in Java inherit the privileges of their enclosing class. Specifically, inner classes have access to the outer class's:
This behavior allows inner classes to encapsulate functionality that is closely tied to the outer class but separates it for readability and maintenance purposes.
Inner classes are essentially members of the outer class, enabling them to access its members, including those marked as private. This access is granted because inner classes:
Thus, the code snippet above is valid because the inner class XYZ has access to the private member x of the outer class ABC, as they are intimately related and encapsulated together in the same class declaration.
The above is the detailed content of Why Can Outer Java Classes Access Inner Class Private Members?. For more information, please follow other related articles on the PHP Chinese website!