简体   繁体   中英

init method in java.util.hashMap

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM