'Restrict a class for creating second object in java
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
}
}
Solution 1:[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;
}
}
Solution 2:[2]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stultuske |
Solution 2 | rlowell |