Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default access modifier for a Java constructor

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

like image 433
nfc-uk Avatar asked Nov 24 '12 12:11

nfc-uk


1 Answers

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.

like image 146
Ian Roberts Avatar answered Sep 28 '22 07:09

Ian Roberts