I recently came across this question and have not been able to find a solution to it. I hope I will get a convincing answer here.
Question : Let A be a non abstract class which is extended (separately) by two classes B and C. Now the task is to allow only one instance of the these classes to be created. If the client code tries to create a second instance of any of these classes, then an exception should be thrown.
A obj11 = new A(); // Fine.
A obj12 = new A(); // thrown an exception.
B obj21 = new B(); // OR
A obj21 = new B(); // both these should be fine
But shouldn't allow 2nd instance of class B to be created.
Thanks in advance.
P.S. : This is different from singleton.
The following should do it. In the real world there should be some synchronized keywords. All crammed into one file for simplicity.
public class A {
static HashSet<Class> thereCanBeOnlyOne = new HashSet();
public A() {
Class c = this.getClass();
if (thereCanBeOnlyOne.contains(c))
throw new RuntimeException();
thereCanBeOnlyOne.add(c);
}
static public class B extends A {}
static public class C extends A {}
public static void main(String[] args) {
A a1 = new A();
B b1 = new B(); // OK
C c1 = new C(); // OK
C c2 = new C(); // throws exception
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With