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?
Here, in the pushToStack method, how can stackOfMyObjects be accessed from 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 MyStack is trusted to use private members declared within MyStack.
See section 6.6 of the JLS for more details. Specifically, in section 6.6.1:
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.
Here, the access does occur within the body of the top level class (MyStack) that encloses the declaration of the stackOfMyObjects variable, so access is permitted.
Because it is of the same Class.
Private is in class scope, not object scope, and so when inside a Class, you can access all private/protected members of the class.
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