I would appreciate an explanation for these questions:
Override a constructor in Java?Constructor be private?<
No, you can't override a constructor. They're not inherited. However, each subclass constructor has to chain either to another constructor within the subclass or to a constructor in the superclass. So for example:
public class Superclass
{
public Superclass(int x) {}
public Superclass(String y) {}
}
public class Subclass extends Superclass
{
public Subclass()
{
super(5); // chain to Superclass(int) constructor
}
}
The implication of constructors not being inherited is that you can't do this:
// Invalid
Subclass x = new Subclass("hello");
As for your second question, yes, a constructor can be private. It can still be called within the class, or any enclosing class. This is common for things like singletons:
public class Singleton
{
private static final Singleton instance = new Singleton();
private Singleton()
{
// Prevent instantiation from the outside world (assuming this isn't
// a nested class)
}
public static Singleton getInstance() {
return instance;
}
}
Private constructors are also used to prevent any instantiation, if you have a utility class which just has static methods.