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

1
  • There's only one way to define a default constructor. What you showed are two ways of creating instances of a class. Commented Jun 8, 2010 at 2:47

3 Answers 3

11
  • 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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it is the term i am looking for.
5

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.