Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why inner class can access to a private member of another inner class? [closed]

Tags:

java

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.

like image 752
user1260771 Avatar asked Aug 07 '13 02:08

user1260771


1 Answers

"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.

like image 112
chrylis -cautiouslyoptimistic- Avatar answered Oct 04 '22 21:10

chrylis -cautiouslyoptimistic-