繁体   English   中英

如何在具有私有构造函数的本地内部类的外部创建实例?

[英]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的对象?

因为Top Level Class是一个幸福的家庭,每个人都可以互相访问,尽管private

JLS 6.6.1

6.6.1。 确定可访问性

  • 只有在类型可访问且声明成员或构造函数允许访问时,才能访问引用(类,接口或数组)类型的成员(类,接口,字段或方法)或类类型的构造函数:
    • 否则,如果成员或构造函数被声明为private ,则当且仅当它发生在包含成员或构造函数声明的顶级类(第7.6节 )的主体内时才允许访问。

你甚至可以访问该类的私有变量(试试吧!)。

这是因为您在调用它的同一个类中定义了该类,因此您具有该类的私有/内部知识。

如果您将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.

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