0

Could the uniqueeInstance have one and only one instance?

public class A {

     private static A uniqueInstance = new A();

     private A() {}

     public static A getInstance() {
            return uniqueInstance;
     }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
zhou.k
  • 1
  • You are looking at what is known as a `singleton`, which is an object (an instance of a Java class in this case) which has only one instance. – Tim Biegeleisen Dec 08 '15 at 05:53
  • It might be useful for you to search the term "Singleton", what it's for and how to correctly implement it. – Acapulco Dec 08 '15 at 05:53
  • 1
    So, you're talking about singletons, I'd suggest doing some research on them. In your case, no, it's possible that `uniqueInstance` might be assigned a new instance (but it will only ever have one) (I believe it has to do with how classloading can work). Generally speaking, it's generally considered a better idea to use a `enum` now days – MadProgrammer Dec 08 '15 at 05:53

2 Answers2

0

This is a Singleton pattern, it's purpose is to have only one possible instance for a class.

This is why you have a private constructor , so that no other class can attempt to instantiate it directly.

Here are more elaborate thoughts for possible uses of a Singleton :

When to use the Singleton

Community
  • 1
  • 1
Arnaud
  • 17,229
  • 3
  • 31
  • 44
0

It is not guaranteed.

By reflection you are easy to get more instances.

The only way to guarantee that you have exactly one instance is to use an enum:

enum Holder {

    INSTANCE;

    //Keep in Mind of A you may still have more instances. if you want to have the
    //guarantee to have only one instance you may need merge the whole class
    //into an enum (which may not be possible)
    public A uniqueInstance = new A();    
}

Other ways like throwing an exception in the constructor are generally also possible. But not completely secure since there are ways to create an Object without calling any constructor.

Denis Lukenich
  • 3,084
  • 1
  • 20
  • 38