Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java access misunderstanding

Tags:

java

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?

like image 482
Babloo Avatar asked Dec 13 '25 01:12

Babloo


2 Answers

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.

like image 133
Jon Skeet Avatar answered Dec 14 '25 16:12

Jon Skeet


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.

like image 22
Nitzan Tomer Avatar answered Dec 14 '25 14:12

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!