Java Docs says interfaces cannot have fields.Why?
interface, java
Solution
How could this be possible because Java Docs also says all fields in interface are `public`, `static` and `final`.
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`, and `final`. 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.
Problem
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`.