[Java] Access to non-accessible member of nested type


(Werner Thumann) #1

The JLS guarantees that private members are accessible from and into nested classes. However, from a design perspective, it is often desirable to achieve a more fine-grained encapsulation for nested types. Therefore, access to private members of a nested class from the enclosing class should not be allowed. Instead, the API of the nested class should be designed to provide the necessary accesses. This also avoids the creation of synthetic accessor methods by the compiler.

Code Smell (Design)


public class AccessToNonAccessibleMemberOfNestedType {

	public static class Nested {
		private int privateVar = 0;
	public static void main(String[] args) {
		Nested n = new Nested();
		n.privateVar = 8; // Noncompliant