Reputation: 49
I've got a question for you? As we all know, interface fields in Java are default public, static and final as well. How about extending interfaces? For example if we have some interface with defined fields in it and we create another interface which extends interface with fields, we shouldn't be able to inherit fields, because they are literally static and also final. But we can! So could you explain it to me why?
interface interfaceWithFields{
String name = "Matthew";}
interface interfaceWithoutFields extends interfaceWithFields{}
And when we call standard output method, it will return Matthew:
System.out.println(interfaceWithoutFields.name); //no problem at all
Thanks in advance for responses. It's late at night and I might have confused something.
Upvotes: 0
Views: 734
Reputation: 37845
This is normal. Subclasses and subinterfaces in general inherit static members from their supertypes.*
9.2:
The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields, classes, and interfaces that it hides; abstract or default methods that it overrides (§9.4.1); and
static
methods.
The wording there is kind of, umm wordy, but it says interfaces inherit static fields from superinterfaces unless they are not hidden. (Hiding is when you declare a variable with the same name.)
In practice, the compiler will just replace interfaceWithoutFields.name
with interfaceWithFields.name
. There is only one static variable name
exists.
* (Except, weirdly, static methods are not inherited from superinterfaces.)
Upvotes: 4
Reputation: 327
I'm not sure if this the technical answer, but in this case it works very similar to how a normal class would work. If you inherit from a Base class with a public, static, or final field, it will also be in the extended class. So at least in that sense it seems reasonable that interfaces would in a similar manner.
Upvotes: 1