简体   繁体   English

当一个成员是私有类实例时,该类如何看到另一个类的公共成员

[英]How can a class see a public member of another class when the member is a private class instance

I am a C++ programmer trying to understand best practices of the Java language. 我是一名C ++程序员,试图了解Java语言的最佳实践。 Please tailor your responses accordingly :) 请相应地调整您的回复:)

I worked out an example and I don't understand why/how the behavior I observed is possible. 我举了一个例子,但我不明白为什么/如何观察到我的行为是可能的。

//HelloWorld.java

public class HelloWorld{
    public static void main(String []args){
        Newfile nf = new Newfile();
        nf.setTest(5);
        System.out.println(Integer.toString(nf.test.i));
        System.out.println("Hello World");
    }
}

//Newfile.java

class TEST {
    public int i;
}

public class Newfile{    
    public TEST test = new TEST();
    public int setTest(int i) {
        return test.i = i;
    }
}

// THIS WORKED 
/*
   5
   Hello World
*/

Since Test is private (well I presume) then how can HelloWorld even manipulate the contents of TEST (ie the i member)? 由于Test是私有的(我想也是这样),那么HelloWorld怎么能操纵TEST的内容(即i成员)?

Now the strange part, when I moved TEST to a private inner class of Newfile it now behave as I would've expected the above experiment to behave and I got: 现在奇怪的一部分,当我移动TEST私人内部类的Newfile现在表现为我所预料的上述实验的行为,我得到:

i in Newfile.TEST is defined in an inaccessible class or interface

Since TEST is private (well I presume) 由于TESTprivate (我想也是)

Nope. 不。 It's actually package-private . 实际上是package-private

From Java Tutorials : Java教程

If a class has no modifier (the default, also known as package-private), it is visible only within its own package 如果一个类没有修饰符(默认值,也称为package-private),则仅在其自己的包中可见


EDIT 编辑

Both your HelloWorld and your TEST classes are members of the same package (in your case, since you don't appear to have specified the package explicitly, they are members of the unnamed package). HelloWorldTEST类都是同一程序包的成员(在您的情况下,由于您似乎未明确指定该程序包,因此它们都是未命名程序包的成员)。 Therefore, even though TEST is package-private, it is accessible from HelloWorld . 因此,即使TEST是包私有的,也可以从HelloWorld访问。

Now the strange part, when I moved TEST to a private inner class of Newfile it now behave as I would've expected the above experiment to behave and I got: 现在最奇怪的部分是,当我将TEST移到Newfile的私有内部类中时,它现在的行为与我期望上述实验的行为一样,我得到了:

 i in Newfile.TEST is defined in an inaccessible class or interface 

By making TEST a private inner class of Newfile you make it accessible only to members of Newfile class itself, so, naturally, it's no longer accessible from HelloWorld in this case. 通过将TEST设为Newfileprivate内部类,您可以使其仅对Newfile类本身的成员可以访问,因此,在这种情况下,自然不能再从HelloWorld进行访问。

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

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