Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Docs says interfaces cannot have fields.Why?

Tags:

java

interface

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.

like image 761
Fresher Avatar asked May 20 '14 13:05

Fresher


2 Answers

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.

like image 70
Luiggi Mendoza Avatar answered Sep 29 '22 16:09

Luiggi Mendoza


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.

like image 29
Tim B Avatar answered Sep 29 '22 15:09

Tim B