I would appreciate an explanation for these questions:
Override
a constructor in Java?Constructor
be private?<
try this : http://www.javabeginner.com/learn-java/java-constructors 1 -> No 2 -> yes
You can not override a constructor, however you can make them any access level modifier such as public, private or default. You would want a private constructor for things like a singleton or for a class that's mostly made of static methods and such (i.e Java's Math class)
You can use callback:
In parent class:
protected void onCreate(){}
SomeClass(){
//Constructor code
onCreate()
}
in child:
@Override
protected void onCreate(){
//Child constructor code
}
no we cannt override an construtor, For implementing Singleton pattren we should have a private construtor.
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.