How to make class to allow creation of 3 objects only
i was asked this question in my interview that how to make a class that can only allows 3 objects creation.
i suggested to take a static variable and a static function for creation of object and while returning reference of new object just check value in static variable to check count of no. of object already created.
second approach i told him to take 3 static object of same class in that class only and let the user use those object only.
please tell me the best approach to perform above operation.
I think your first approach is closer to the question: make private constructor and a static newInstance() method that checks how many instances were created before and returns null if it's more than 3.
Second approach is also ok, though.
EDIT @Saurabh: even though the question says nothing about what to do in case the object is gc-ed, let's develop this:
- A dirty hack to the first solution: override finalize() method that decrements the static counter of objects.
- A pool of objects with some sort of a locking mechanism that only allows three, let's say, users, use the objects ate the same time.
In Java, the simplest solution would be to use an enum.