Question

I've been wondering why it's allowed to do a code implementation in an interface, when interfaces are suppossed to contain no code implementation:

public interface someInterface{
String someString = "example";   
}

I can make a class implement this interface, without getting an error:

public class someClass implements someInterface

How come?

Was it helpful?

Solution

You are allowed to declare constants in interfaces, which is what you have done. You have not implemented code.

Variables declared in interfaces are implicitly declared public static final.

The JLS, Section 9.3, covers this:

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.

OTHER TIPS

According to java docs

Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

Here you are not defined any methods to implement.So you didn't get any error here.

There is no strict condition that an interface must have signatured methods.Remember there are Marker Interfaces too in java.

And secondly , You can declare variables inside interface.

And that variable someString assigned in a static context and shared across all the implemntations by that interface

Point is that the variables inside declared interface are implicitly static and final.You can use them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top