I was asked this question in an interview.
There are 3 classes A
, B extends A
& C extends B
. We have to design these classes conforming to these constraints
- Client can instantiate only one instance of
A
, one instance ofB
& one instance ofC
using their default constructor withnew
keyword. - Trying to create another instance of any of these class will result in an exception.
- The designer of the class have to enforce the above 2 rules, so that client will experience the above rules implicitly (i.e. it should not be the responsibility of client to conform to above rules).
I suggested an approach using an static Map<Class, Object>
. So for e.g. when somebody called new B()
it would check if map.contains(B.class)
. If yes then throw exception & if not then save instance in map & let the object be created.
But the next question was how would I enforce this approach on each class? As per my approach each constructor would have to carefully populate the map otherwise it will break the constraint.
How would I solve this problem?