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.
Thanks
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:
finalize()method that decrements the static counter of objects.