简体   繁体   中英

java interface memory usage when implemented by multiple classes

I have an Interface with a bunch of declared fields. For each class that implements this interface does it need to load all the fields into memory or does it load into memory once?

Only static fields are defined in an interface and static fields are loaded a single time, that is as the class is loaded.
So no you would not have any duplicated fields for these whatever the number of class that implements the interface.

The JLS. Chapter 8. Classes states :

8.3.1.1. static Fields

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

By the way, defining static fields in an interface is often a bad smell.

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