views:

139

answers:

3

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

+11  A: 
  • Class A is supposed to be a Singleton, where you can only have one instance of A. You retrieve that single instance by calling getInstance();

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

There are a few ways to go about this depending on your requirements:

public class A{
    private static A instance = new A();
    private A(){} // private constructor
    public static A getInstance() {return instance;}
}

or not creating the instance until the first call

public class A{
    private static A instance = null;
    private A(){} // private constructor
    public static A getInstance() {
        if(instance == null){
           instance = new A(); // create the one instance.
        }
        return instance;
    }
}
  • Class B is a class with a no-parameter constructor. You can create as many B instances as you want by calling new B();
Bakkal
Thanks, it is the term i am looking for.
aladine
+5  A: 

It looks like A is an attempt at implementing the singleton pattern, but it's not quite right - it should have a private constructor:

class A {
 private static final A INSTANCE = new A();
 private A() { }
 public static A getInstance() { return INSTANCE; }
}

This ensures that only one instance of A ever exists in your application - if any other object needs to use an instance of A to do something, the only way it can get one is via the getInstance() method, which returns the same instance all the time.

With B, you can have as many instances of B as needed/desired, and any other object is free to make a new instance of B if it chooses.

Chris Smith
Thanks. it is very clear answer
aladine
+1  A: 

In the first case, only one instance available. In the second case, one can have as many as possible. You need to make the constructor private in the in the first case.

fastcodejava