Java构造函数的默认访问修饰符 [英] Default access modifier for a Java constructor

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

问题描述

任何人都可以解释一个显式无参构造函数(和其他构造函数)的默认访问修饰符。

Can anybody explain what the default access modifier is for an explicit no-arg constructor (and other constructors)?

推荐答案

构造函数与这方面的方法相同 - 如果你不给一个显式的public,private或protected,那么构造函数得到默认的package private可见性。它可以从同一个类或同一个包中的任何其他类调用,但不能从不同包中的子类调用(因此如果一个类只有package-visible构造函数,那么任何子类必须在同一个包中)。

Constructors are the same as methods in this respect - if you don't give an explicit public, private or protected then the constructor gets the default "package private" visibility. It can be called from within the same class or from any other class in the same package, but not from subclasses in a different package (so if a class has only package-visible constructors then any subclasses must be in the same package).

私有构造函数阻止任何其他类实例化此类,但您可以在类中调用自己的私有构造函数。这是类似单例的常见模式。

A private constructor prevents any other class from instantiating this one, but you can have a public static factory method within the class that calls its own private constructor. This is a common pattern for things like singletons.

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

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