gpt4 book ai didi

java - java中默认构造函数的访问修饰符是什么?

转载 作者:IT老高 更新时间:2023-10-28 21:08:10 26 4
gpt4 key购买 nike

我们都知道,如果不专门定义构造函数,编译器会插入一个不可见的零参数构造函数。我认为它的访问修饰符是公开的,但在处理内部类问题时,我发现我可能错了。这是我的代码:

public class Outer {
protected class ProtectedInner {
// adding a public constructor will solve the error in SubOuterInAnotherPackage class
//public ProtectedInner() {}
}
}

另外一个包里还有一个Outer的子类:

public class SubOuterInAnotherPackage extends Outer {
public static void main(String[] args) {
SubOuterInAnotherPackage.ProtectedInner protectedInner
= new SubOuterInAnotherPackage().new ProtectedInner(); // Error!! Can't access the default constructor
}
}

你会在 main() 方法中得到一个错误,但是如果你向 ProtectedInner 类添加一个公共(public)构造函数,这个错误就解决了。这就是为什么我认为默认构造函数的修饰符不是公共(public)的!那么谁能告诉我默认构造函数的访问修饰符是什么?

最佳答案

I thought its access modifier is public, but when I deal with a inner class issue, I found maybe I was wrong.

是的。事实上,几年前我发现自己处于同样的境地。我对一个错误感到惊讶(通过 Guice 注入(inject),这使它更难找到)。

关键是检查规范,在本例中为 section 8.8.9 :

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

所以在这种情况下,你的构造函数被隐式protected

关于java - java中默认构造函数的访问修饰符是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22007143/

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