Default and Parameterized Constructors
Java memory model
-
instances are created inside the heap
-
if you want to use super(), i.e. parent class constructor, then it must be the first statement inside the constructor.
public class Employee{
public Employee(){
}
public Employee(String firstName){
this(); // calling default constructor
}
public Employee(String firstName, String lastName){
this(firstName); // calling constructor with single argument of String type
}
}public class Parent{
public Parent(){
//...
}
}
public class Child extends Parent{
public Child(){
super(); // invokes Parent's constructor
}
}- used in
Singleton Pattern
A common singleton class definition looks like this:
import java.io.Serializable;
public class DemoSingleton implements Serializable{
private static final long serialVersionUID = 1L;
private DemoSingleton(){
// private constructor
}
private static class DemoSingletonHolder{
public static final DemoSingleton INSTANCE = new DemoSingleton();
}
public static DemoSingleton getInstance(){
return DemoSingletonHolder.INSTANCE;
}
protected Object readResolve(){
return getInstance();
}
}