Fresher
Fresher

Reputation: 892

Java Docs says interfaces cannot have fields.Why?

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.

Upvotes: 6

Views: 2280

Answers (3)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 6

Sajan Chandran
Sajan Chandran

Reputation: 11487

When an object is created using new all the fields will be initialised either to its value or its default value. Since you cannot instantiate an interface you cannot have any fields. But you can have constants in your interface and thats why all fields by default are public static final

See jls

Upvotes: 2

Tim B
Tim B

Reputation: 41188

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.

Upvotes: 3

Related Questions