Abhishek Keshri
Abhishek Keshri

Reputation: 3234

Do inner classes invalidate the concept of Encapsulation?

The private access modifier is used so that we can use the respective member only within the class. But using inner classes, we can define a method to access the private members of the outer class. Here is the code for that:

import java.util.*;
import java.lang.*;
import java.io.*;

class Outer {
    private int x = 1;

    Inner getInner() {
        Inner inner = new Inner();
        return inner;
    }

    class Inner {
        int getX() {
            return x;
        }
    }
}

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Outer outer = new Outer();
        Outer.Inner inner = outer.getInner();
        System.out.println("Private x: "+inner.getX());
    }
}

Doesn't it go against the concept of Encapsulation?

Upvotes: 3

Views: 1040

Answers (2)

memo
memo

Reputation: 1938

The private access modifier is used so that we can use the respective member only within the class.

Since the inner class is part of the class, this still holds. The access to private data is confined within, so encapsulation is preserved. Besides, since you're able to modify the source file of the class, it means you have access to all its internals anyway.

Upvotes: 3

Igor O.
Igor O.

Reputation: 193

The "Inner" class is a part of the "capsule" - the Outer class. So it is absolutely ok, that it can access private variables of the Outer class. The point of Encapsulation is to hide parts of implementation from the outside and the "Inner" class is not outside, it is inside the class.

Upvotes: 1

Related Questions