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?
Asked
Active
Viewed 300 times
0
-
2Show us the code that you speak of – Luke Garrigan Apr 05 '18 at 13:00
1 Answers
0
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.

davidxxx
- 125,838
- 23
- 214
- 215
-
1As an addendum, loading and even using a class implementing an interface does not necessarily cause the initialization of the interface. Only one of the events specified in [JLS§12.4.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.1) may cause the initialization, so it’s even possible to use one or more classes implementing an interface whose fields are not initialized at all at runtime, not even a single time. – Holger Apr 06 '18 at 12:43
-
@Holger Very interesting section. About " loading and even using a class implementing an interface does not necessarily cause the initialization of the interface" Are you sure ? The specification says "When a class is initialized, its superclasses are initialized". Do you have you an example where the interface would not be loaded while the class implementing would ? – davidxxx Apr 10 '18 at 06:32
-
“When a class is initialized, its superclasses are initialized” has be taken literally, “superclasses” not “superinterfaces”. Note the subsequent “as well as any superinterfaces that declare any default methods”, which excludes interfaces without default methods. It happens that I once [made an example](https://stackoverflow.com/a/19723562/2711488)… – Holger Apr 10 '18 at 06:52
-
It seems you missed that “made an example” of my previous comment is a link to that example. Note that being “loaded” does not imply getting “initialized”. – Holger Apr 10 '18 at 08:04
-
@Holder I didn't miss the text but the link yes :) Sorry I am testing a monochrome monitor (E-Ink). So I didn't see it. Very interesting example (+1)! You absolutely right about loading and initializing. Thanks :) – davidxxx Apr 10 '18 at 08:22