Please advise me the difference between two ways of declaration of java constructor
public class A{
private static A instance = new A();
public static A getInstance() { return instance;
}
public static void main(String[] args) {
A a= A.getInstance();
}
}
AND
public class B{
public B(){};
public static void main(String[] args) {
B b= new B();
}
}
Thanks
Ais supposed to be a Singleton, where you can only have one instance of A. You retrieve that single instance by callinggetInstance();There are a few ways to go about this depending on your requirements:
or not creating the instance until the first call
Bis a class with a no-parameter constructor. You can create as many B instances as you want by callingnew B();