简体   繁体   English

Java访问误解

[英]Java access misunderstanding

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? 这里,在pushToStack方法,怎么能myStack2stackOfMyObjects成员,事件虽然stackOfMyObjects已定义的私有?

Here, in the pushToStack method, how can stackOfMyObjects be accessed from myStack2, event though stackOfMyObjects has been defined private? 这里,在pushToStack方法中,如何通过myStack2访问stackOfMyObjects,虽然stackOfMyObjects已被定义为private?

Because it's still a MyStack . 因为它仍然是MyStack Access control in Java is about where the code appears, not whether it's accessing a "different" object. Java中的访问控制是关于代码出现的位置,而不是它是否访问“不同”对象。

Basically, all code within MyStack is trusted to use private members declared within MyStack . 基本上, MyStack所有代码都被信任使用MyStack声明的私有成员。

See section 6.6 of the JLS for more details. 有关更多详细信息,请参见JLS的6.6节 Specifically, in section 6.6.1: 具体而言,在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. 否则,如果成员或构造函数被声明为private,则当且仅当它发生在包含成员或构造函数声明的顶级类(第7.6节)的主体内时才允许访问。

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. 这里,访问确实发生在顶级类( MyStack )的主体内,它包含了stackOfMyObjects变量的声明,因此允许访问。

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. Private属于类范围,而不是对象范围,因此当在Class中时,您可以访问该类的所有私有/受保护成员。

I assume that myStack2 is of Type MyStack . 我假设myStack2MyStack类型。 stackOfMyObjects is defined private yes, but its still in the same Class MyStack. stackOfMyObjects被定义为private yes,但它仍然在同一个 MyStack中。 It's a global defined variable, which can be accessed from all Objects, which have been created from this class.. 它是一个全局定义的变量,可以从所有从这个类创建的对象访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM