I was reading this and it clearly states that One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot.
How could this be possible because Java Docs also says all fields in interface are public,static and final
.
How could this be possible because Java Docs also says all fields in interface are
public
,static
andfinal
.
From Java Language Specification. Chapter 9. Interfaces. 9.3. Field (Constant) Declarations (emphasis mine):
Every field declaration in the body of an interface is implicitly
public
,static
, andfinal
. It is permitted to redundantly specify any or all of these modifiers for such fields.If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for
ConstantModifier
.
This means that every field in the interface will be considered as a public
constant field. If you add public
, static
and final
or some of these modifiers or none of them, the compiler will add them for you. That's the meaning of implicitly.
So, having this:
interface Foo {
String bar = "Hello World";
}
Is similar to have
interface Foo {
public String bar = "Hello World";
}
That is similar to
interface Foo {
static bar = "Hello World";
}
The three interfaces will compile to the same bytecode.
Also, make sure that your fields declaration in an interface follow the subnote. This means, you cannot narrow the visibility of a field in an interface. This is illegal:
interface Foo {
//compiler error!
private String bar = "Hello World";
}
Because bar
won't be public
and it defies the standar definition for fields in an interface.
A static final
field is a constant value and is present in the class itself, not in an instance of the class. The instance of the interface cannot have any fields, even though the Interface itself may, and even on the Interface itself you are limited to defining constants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With