Why does the following code compile fine?
public class MyStack {
private static MyStack myStack ;
private Stack<MyObject> stackOfMyObjects;
private MyStack() {
stackOfMyObjects = new Stack<MyObject>() ;
}
public static void pushToStack(MyObject myObject, MyStack myStack2) {
myStack2.stackOfMyObjects.push(myObject) ;
}
}
Here, in the pushToStack method, how can the stackOfMyObjects member of myStack2, event though stackOfMyObjects has been defined private?
Because it’s still a
MyStack. Access control in Java is about where the code appears, not whether it’s accessing a “different” object.Basically, all code within
MyStackis trusted to use private members declared withinMyStack.See section 6.6 of the JLS for more details. Specifically, in section 6.6.1:
Here, the access does occur within the body of the top level class (
MyStack) that encloses the declaration of thestackOfMyObjectsvariable, so access is permitted.