Constructor's Private scope
Given this code snippet, could you explain why it woks?
The thing is that the class constructor is marked private, so should not it preven开发者_运维百科t us to call it with new operator?
public class Alpha {
protected Alpha() {}
}
class SubAlpha extends Alpha {
private SubAlpha() {System.out.println("ok");}
public static void main(String args[]) {
new SubAlpha();
}
}
It all works because the static method is part of the class and it can see all private fields and methods, right? Outside this "new" initialization would never work?
The only private
constructor in your question is SubAlpha
, which SubAlpha
itself is calling. There's no issue, a class can call its own private methods. The Alpha
constructor is protected
, so SubAlpha
has access to it.
Edit: Re your edit: Yes, exactly. A separate class (whether a subclass or not) would not have access to SubAlpha
's private constructor and could not successfully construct a new SubAlpha()
.
Example 1:
public class Beta
{
public static final void main(String[] args)
{
new SubAlpha();
// ^--- Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error
}
}
Example 2:
public class SubSubAlpha extends SubAlpha
{
private subsubAlpha()
{
// ^== Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error because of the implicit call to super()
}
}
This is, of course, constructor-specific, since scope is always member-specific. If a class has a different constructor with a different signature and a less restrictive scope, then a class using it (including a subclass) can use that other constructor signature. (In the case of a subclass, that would require an explicit call to super(args);
.)
The code works as the main method is also in the same class. You may not be able to initialize SubAplha from a different class.
精彩评论