Java中默认构造函数的访问修饰符是什么? [英] What's the access modifier of the default constructor in java?

查看:470
本文介绍了Java中默认构造函数的访问修饰符是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We all know that if we don't specifically define a constructor, the compiler inserts an invisible zero-parameter constructor. I thought its access modifier was public, but in dealing with an inner class issue, I found maybe I was wrong. Here is my code:

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

在另一个包中有外部的子类:

And there is a subclass of Outer in another package:

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 类中,则该错误已解决。这就是为什么我认为默认构造函数的修饰符不是公开的!谁能告诉我默认构造函数的访问修饰符是什么?

You will get an error in the main() method, but if you add a public constructor to the ProtectedInner class, that error is solved. That's why I'm thinking that the modifier of the default constructor is not public! So could anyone tell me what the access modifier of the default constructor is?

推荐答案


我认为访问修饰符是公共的,但是当我处理一个内部类问题时,我发现也许我错了。

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

是的。确实,几年前,我发现自己处在相同的境地。我对一个错误感到惊讶(通过Guice注入,这使查找起来有点困难)。

Yup. Indeed, I found myself in the same situation a couple of years ago. I was surprised by an error (through Guice injection, which made it slightly harder to find).

关键是要检查规格,在这种情况下,第8.8.9节

The key is to check the spec, in this case section 8.8.9:


在类类型中,如果将该类声明为public,则默认构造函数将隐式赋予访问修饰符public(第6.6节);如果该类被声明为受保护的,则默认构造函数被隐式赋予访问修饰符保护(第6.6节);如果该类被声明为私有,则默认构造函数被隐式赋予访问修饰符私有(第6.6节);否则,默认构造函数将具有没有访问修饰符暗含的默认访问权限。

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.

因此,在这种情况下,您的构造函数隐式地受保护的

So in this case, your constructor is implicitly protected.

这篇关于Java中默认构造函数的访问修饰符是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆