Amazon Interview Question
Software Engineer / Developersi) Inheriting a singleton class should be prohibited. Making a singleton class inheritable means any number of child classes can inherit from it creating multiple instances of the singleton class which will obviously violate the principle of singletons.
ii) We will be able to create a copy of the Object by cloning it using the Object’s clone method.. To avoid this, you need to override the Object’s clone method, which throws a CloneNotSupportedException exception:
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
iii) If Singleton Class implements the Serializable interface, then instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances. To avoid the above you need to implement readResolve() method.
private Object readResolve() {
return INSTANCE;
}
limitations:
- master January 03, 2010Implementation of serialization and cloneable causes the problem.
In the Distributed computing and in multiple class loader there is a chance of multiple objects getting created.
Subclassing if done, there if not implemented correctly it could cause more problem with multiple objects.