gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:54 26 4
gpt4 key购买 nike

考虑以下程序:

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");
}
}

输出:本地的主

具有私有(private)构造函数的类意味着我们只能在类内部创建对象,但在这里可以在类外部创建实例。有人能解释一下我们如何在 B 类之外创建 B 的对象吗??

最佳答案

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

JLS 6.6.1

6.6.1. Determining Accessibility

  • A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    • 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.

关于java - 如何在具有私有(private)构造函数的本地内部类的类外部创建实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17133003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com