0

Is there a way where we can restrict a class to create only a single object in java? It should give some exceptions if we try to create another new object. Example:

class A {}
public class Test {

    public static void main(String[] args) {

    A a1 =new A(); //This should be allowed
    A a2 =new A(); // This should not be allowed

    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
achan1989
  • 101
  • 2
  • 10
  • 7
    you mean prevent more than one instance of A to be created, or don't allow A to create more than one Object? If it's the former, you're looking for the Singleton pattern – Stultuske May 13 '22 at 10:11
  • https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples – Stultuske May 13 '22 at 10:12
  • Yes. The pattern should be singleton we can say.. but it should allow creating the first object using new.. and it should not allow creating any more objects. – achan1989 May 13 '22 at 10:13
  • @achan1989 I've already voted for the suggestion of the singleton pattern usage, but is there any chanse that you could share the reason why you need such mechanism? – Kamil May 13 '22 at 10:13
  • Use a `static` field that determines if a new instance can be created. – Johannes Kuhn May 13 '22 at 10:15
  • 1
    Do you really want to get an exception for a second instantiation attempt? There are mechanisms to prevent the attempt beforehand, i.e. at compile-time. – Holger May 13 '22 at 10:15
  • @Holger yes. It should give exception at compile time. – achan1989 May 13 '22 at 10:20
  • @Kamil Actually I have come across this question while giving an interview. And I don't find any way to do it. – achan1989 May 13 '22 at 10:21
  • 2
    Don’t confuse exceptions and compiler errors. So read [What is an efficient way to implement a singleton pattern in Java?](https://stackoverflow.com/q/70689/2711488) – Holger May 13 '22 at 10:22
  • 2
    "It should give exception at compile time" => either it doesn't compile, or it throws an exception when executed (at runtime). The standard compiler will always let you compile that code even if it then fails at runtime. So if you really want to make it fail at compile time, you should pre-process it (for example with an annotation processor or a custom maven plugin). Even though I really think you simply want a Singleton pattern. – Matteo NNZ May 13 '22 at 10:24

2 Answers2

1

to try your additional requirement:

This should work, but I don't really see a point to it.

public class A {

  private static boolean instantiated;

  public A() throws Exception {
    if ( instantiated ) {
      throw new Exception("Already instantiated");
    }
    instantiated = true;
  }
}
Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • 4
    But mind that this is not thread safe. – Holger May 13 '22 at 10:16
  • indeed not. Then again, I don't really see a reason to ever implement something like this, when the option of a singleton exists, so I won't delve deeper into it. – Stultuske May 13 '22 at 10:17
  • One possible reason could be to instantiate with constructor arguments, something not possible with eager initialization such as by using an enum. There are already numerous examples on the Internet showing how to do this. – k314159 May 13 '22 at 11:08
  • @k314159 noone said it's impossible to pass parameters to a getInstance method – Stultuske May 13 '22 at 11:16
  • I agree that a getInstance method is a good alternative to calling a constructor and you can indeed pass parameters. The getInstance method is lazy initialization. I said it's impossible to pass parameters with eager initialization. – k314159 May 13 '22 at 11:19
-1

You can use the special Singleton pattern. Most of the examples are on the internet.

    public class Singleton {
    private static Singleton instance;

    public static synchronized Singleton getInstance() {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }
}
rlowell
  • 66
  • 5