簡體   English   中英

當一個成員是私有類實例時,該類如何看到另一個類的公共成員

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

我是一名C ++程序員,試圖了解Java語言的最佳實踐。 請相應地調整您的回復:)

我舉了一個例子,但我不明白為什么/如何觀察到我的行為是可能的。

//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
*/

由於Test是私有的(我想也是這樣),那么HelloWorld怎么能操縱TEST的內容(即i成員)?

現在奇怪的一部分,當我移動TEST私人內部類的Newfile現在表現為我所預料的上述實驗的行為,我得到:

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

由於TESTprivate (我想也是)

不。 實際上是package-private

Java教程

如果一個類沒有修飾符(默認值,也稱為package-private),則僅在其自己的包中可見


編輯

HelloWorldTEST類都是同一程序包的成員(在您的情況下,由於您似乎未明確指定該程序包,因此它們都是未命名程序包的成員)。 因此,即使TEST是包私有的,也可以從HelloWorld訪問。

現在最奇怪的部分是,當我將TEST移到Newfile的私有內部類中時,它現在的行為與我期望上述實驗的行為一樣,我得到了:

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

通過將TEST設為Newfileprivate內部類,您可以使其僅對Newfile類本身的成員可以訪問,因此,在這種情況下,自然不能再從HelloWorld進行訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM