Igor Ševo Igor Ševo - 2 months ago 9
Java Question

Breaking encapsulation and information hiding in Java

Consider the following snippet.

package breakoop;

public class BreakOOP {

public static class A{
private int a;

public static class B extends A{
public int f(){
return super.a;

public static void main(String[] args) {
B b = new B();

The example only compiles if
are encapsulated within the

This seems to go against some of the fundamental concepts of OOP. Can someone explain why this compiles? What is the reasoning behind it?


Check this: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html. It says it increases encapsulation by allowing the static class to access private members of the top level class (sometimes you may need to do that). And a is private member of class A, which is in the scope of BreakOOP, which in turn makes it accessible inside class B.