[英]How is it possible to create instance outside class of local inner class having private constructor?
考慮以下程序:
public class A
{
public static void main(String[] args)
{
class B
{
private B()
{
System.out.println("local");
}
}
// how are we able to create the object of the class having private constructor
// of this class.
B b1= new B();
System.out.println("main");
}
}
輸出:本地主要
具有私有構造函數的類意味着我們只能在類中創建對象,但是這里可以在類之外創建實例。 有人可以解釋我們如何能夠在B類之外創建B的對象?
你甚至可以訪問該類的私有變量(試試吧!)。
這是因為您在調用它的同一個類中定義了該類,因此您具有該類的私有/內部知識。
如果您將B類移到A類之外,它將按預期工作。
參考JLS 6.6.1 :
否則,如果成員或構造函數被聲明為private,則當且僅當它發生在包含成員或構造函數聲明的頂級類(第7.6節)的主體內時才允許訪問。
實現它的方法是使用合成的包保護方法。
“如果你想隱藏你的內部類的私有成員,你可以定義一個與公共成員的接口,並創建一個實現這個接口的匿名內部類。請參閱此代碼:”
class ABC{
private interface MyInterface{
public void printInt();
}
private static MyInterface mMember = new MyInterface(){
private int x=10;
public void printInt(){
System.out.println(String.valueOf(x));
}
};
public static void main(String... args){
System.out.println("Hello :: "+mMember.x); ///not allowed
mMember.printInt(); // allowed
}
}
你之前這么說
A class having private constructor means we can create object inside the class only
但
這是因為您在main(String[] args) method
定義了inner Class
而不是在Top Level Class
如果你試試
public class A {
class B {
private B() {
System.out.println("local");
}
}
public static void main(String[] args) {
B b1 = new B(); // you cant create object of inner Class B
System.out.println("main");
}
}
然后你不能創建內部B類的對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.