Igor Ševo
Igor Ševo

Reputation: 5515

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();
        System.out.println(b.f());
    }
}

The example only compiles if A and B are encapsulated within the BreakOOP class.

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

Upvotes: 4

Views: 1065

Answers (2)

Thomas
Thomas

Reputation: 88707

The Java Language Specification states:

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

Since classes A and B are defined within the body of BreakOOP that rule applies and B can see private members of A.

As for the OOP concepts: since A and B are static inner classes they don't have the special life-cycle relation with BreakOOP that true inner classes have (i.e. you don't need an instance of BreakOOP to create a new instance of A or B but they still have a somewhat special relation in that they have access to private members. If they should not have that kind of relationship then they shouldn't be inner classes but true top level classes.

Upvotes: 1

uoyilmaz
uoyilmaz

Reputation: 3105

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.

Upvotes: 3

Related Questions