Can anybody explain what the default access modifier is for an explicit no-arg constructor (and other constructors)?
问题:
回答1:
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.
回答2:
JLS 8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
if the class is declared public, then the default constructor is implicitly given the access modifier public;
if the class is declared protected, then the default constructor is implicitly given the access modifier protected;
if the class is declared private, then the default constructor is implicitly given the access modifier private; otherwise,
the default constructor has the default access implied by no access modifier.
回答3:
- A constructor
will have a access-control of type default
when no access-modifier is defined explicitly. So this constructor will have a Package Level Access. Classes which are defined within that package as that of the class with this default constructor will be able to access it and also the classes that extend this class containing the default constructor will be able to access it via inheritance.
- If the constructor is made private
, then only the code within that class can access this.
Singleton example
public class Test {
private static Test uniqueInstance = new Test();
private Test(){}
public static Test getInstance(){
return uniqueInstance;
}
}
- Even non-static inner classes
with in the class has access to its Private memebers and vice-versa.
Eg:
public class T {
private T(){
System.out.println("Hello");
}
class TT{
public TT(){
new T();
}
}
public static void main(String[] args){
T t = new T();
T.TT i = t.new TT();
}
}
回答4:
It differs depending on whether you're writing a constructor for a regular class or an enum:
For classes, the answer is given by JLS §6.6.1:
A class member or constructor declared without an access modifier implicitly has package access.
For enums, the answer is given by JLS §8.9.2:
In an enum declaration, a constructor declaration with no access modifiers is private.
(Enum constructors are always private to prevent other classes instantiating more enum constants.)