作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
考虑以下程序:
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
,每个人都可以互相访问。
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/
我是一名优秀的程序员,十分优秀!