5

I just found out that an inner class can access another inner class's private member like this:

public class TestOutter {
    class TestInner1 {
        private int mInt = 1;
    }
    class TestInner2 {
        public int foo(TestInner1 value) {
            return value.mInt;
        }
    }
}

Method foo of TestInner2 can access the private member mInt of TestInner1.

But I have never see this case before. I don't know the meaning of letting code in TestInner2 can access to the private member of TestInner1.

I was searched about inner class in google, none of the search results shows that inner class have this feature. I also look up to The Java Language Specification, but it still not mention about that.

Roman C
  • 49,761
  • 33
  • 66
  • 176
user1260771
  • 117
  • 2
  • 7
  • pretty much everything inside an "outer" class definition can access private members. – jtahlborn Aug 07 '13 at 02:59
  • 1
    You can refer this question http://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members?lq=1 – SanthyReddy Aug 07 '13 at 03:00
  • Why is this logic worng for you? `TestInner2` is an integral part of `TestOutter` and since `TestOutter` have access to `TestInner1` so does `TestInner2`. It seems fine to me. – Ran Eldan Aug 07 '13 at 03:03
  • Because that's the way they designed it. – user207421 Aug 07 '13 at 03:16

2 Answers2

4

"Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor." JLS 6.6.1 In this case, TestOutter is the top-level class, so all private fields inside it are visible.

Basically, the purpose of declaring a member private is to help ensure correctness by keeping other classes (subclasses or otherwise) from meddling with it. Since a top-level class is the Java compilation unit, the spec assumes that access within the same file has been appropriately managed.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
2

This is because the inner class, as a member of the outer class, has access to all the private variables of its outer class. And since the other inner class is also a member of the outer class, all of its private variables are accessible as well.

Edit: Think of it like you have a couple of couch cushion forts(inner classes) in a house(outer class), one yours the other your siblings. Your forts are both in the house so you have access to all the things in your house. And mom(Java) is being totally lame and saying you have to share with your sibling because everything in the house is everyone elses and if you want your own fort you are going to have to buy it with your own money(make another class?).

unit_25o1
  • 31
  • 1
  • 4