Suppose there are three classes namely A, B and C such that B extends A, C extends B.
Requirement is that client code should be able to call the constructors of each class only once successfully. Upon trying to call constructor twice it should throw an exception.
How can I implement this in Java if duplication of code is not permitted in the child classes?
Example :
public class A {
private static A instance;
public A() {
if (instance != null) {
throw new IllegalArgumentException();
}
instance = this;
}
}
public class B extends A {
private static B instance;
public B() {
if (instance != null) {
throw new IllegalArgumentException();
}
instance = this;
}
}
public class C extends B {
private static C instance;
public C() {
if (instance != null) {
throw new IllegalArgumentException();
}
instance = this;
}
}
public class Driver {
public static void main(String[] args) {
A a1 = new A();
B b1 = new B(); //throwing IllegalArgumentException, it should not throw
}
}
Things I tried.
Maintaining a private static reference of the respective class type which is initially set as null. In the constructor block I added a null check to assign this reference to the static reference. Did not work as I could not avoid duplicating code.
Requirement
//this should work fine
A a1 = new A();
B b1 = new B();
C c1 = new C();
---------------
//this should throw runtime exception
A a1 = new A();
A a2 = new A();
B b1 = new B();
---------------
//this should throw runtime exception
A a1 = new A();
B b1 = new B();
B b2 = new B();
---------------
//this should throw runtime exception
A a1 = new A();
B b1 = new B();
C c1 = new C();
C c2 = new C();
I hope I am clear with the requirements