while I was going through the source code of java.util.HashMap
I found declaration of init
.
Initialization hook for subclasses. This method is called in all constructors and pseudo-constructors (clone
, readObject
) after HashMap
has been initialized but before any entries have been inserted. (In the absence of this method, readObject
would require explicit knowledge of subclasses.)
void init() {
}
I found a related question In Java, is there a legitimate reason to call a non-final method from a class constructor?
But still I am not able to understand what's the purpose of init and why readObject
require explicit knowledge of subclass? Could any one explain with an example
As the comment says, it's an initialization hook for subclasses. Every subclass can override init()
appropriately to perform whatever initialization is required in every case, without having to provide another implementation of readObject
for deserialization and reimplement clone()
themselves.
For example, in LinkedHashMap
, the init()
method is overridden to set up the linked list. Think about where that would happen when deserializing if init()
wasn't available.
See more on this question at Stackoverflow