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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With