Why are all fields in an interface implicitly static and final?

JavaInterfaceStaticFinalLanguage Implementation

Java Problem Overview


I am just trying to understand why all fields defined in an Interface are implicitly static and final. The idea of keeping fields static makes sense to me as you can't have objects of an interface but why they are final (implicitly)?

Any one knows why Java designers went with making the fields in an interface static and final?

Java Solutions


Solution 1 - Java

An interface is intended to specify an interaction contract, not implementation details. A developer should be able to use an implementation just by looking at the interface, and not have to look inside the class which implements it.

An interface does not allow you to create an instance of it, because you cannot specify constructors. So it cannot have instance state, although interface fields can define constants, which are implicitly static and final.

You cannot specify method bodies or initializer blocks in an interface, although since Java 8 you can specify default methods with bodies. This feature is intended to allow new methods to be added to existing interfaces without having to update all the implementations. But you still cannot execute such a method, without first creating an instance implementing the interface.

Aside: Note that you can implement an interface with an anonymous inner class:

interface Foo {
    String bar();
}

class FooBar {
    Foo anonymous = new Foo() {
         public String bar() {
             return "The Laundromat Café";
    };
}

You have to provide the full implementation of the interface for the anonymous inner class to compile.

new Foo() is initializing the anonymous inner class with its default constructor.

Solution 2 - Java

Reason for being final

Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation. An interface is a pure specification without any implementation.

Reason for being static

If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.

Solution 3 - Java

There are a couple of points glossed over here:

Just because fields in an interface are implicitly static final does not mean they must be compile-time constants, or even immutable. You can define e.g.

> interface I { > String TOKEN = SomeOtherClass.heavyComputation(); > JButton BAD_IDEA = new JButton("hello"); > }

(Beware that doing this inside an annotation definition can confuse javac, relating to the fact that the above actually compiles to a static initializer.)

Also, the reason for this restriction is more stylistic than technical, and a lot of people would like to see it be relaxed.

Solution 4 - Java

The fields must be static because they can't be abstract (like methods can). Because they can't be abstract, the implementers will not be able to logically provide the different implementation of the fields.

The fields must be final, I think, because the fields may be accessed by many different implementers allows they to be changeable might be problematic (as synchronization). Also to avoid it to be re-implemented (hidden).

Just my thought.

Solution 5 - Java

I consider the requirement that the fields be final as unduly restrictive and a mistake by the Java language designers. There are times, e.g. tree handling, when you need to set constants in the implementation which are required to perform operations on an object of the interface type. Selecting a code path on the implementing class is a kludge. The workaround which I use is to define an interface function and implement it by returning a literal:

public interface iMine {
    String __ImplementationConstant();
    ...
}

public class AClass implements iMine {
    public String __ImplementationConstant(){
        return "AClass value for the Implementation Constant";
    }
    ...
}

public class BClass implements iMine {
    public String __ImplementationConstant(){
        return "BClass value for the Implementation Constant";
    }
    ...
}

However, it would be simpler, clearer and less prone to aberrant implementation to use this syntax:

public interface iMine {
    String __ImplementationConstant;
    ...
}

public class AClass implements iMine {
    public static String __ImplementationConstant =
        "AClass value for the Implementation Constant";
    ...
}

public class BClass implements iMine {
    public static String __ImplementationConstant =
        "BClass value for the Implementation Constant";
    ...
}

Solution 6 - Java

Specification, contracts... The machine instruction for field access uses object address plus field offset. Since classes can implement many interfaces, there is no way to make non-final interface field to have the same offset in all classes that extend this interface. Therefore different mechanism for field access must be implemented: two memory accesses (get field offset, get field value) instead of one plus maintaining kind of virtual field table (analog of virtual method table). Guess they just didn't want to complicate jvm for functionality that can be easily simulated via existing stuff (methods).

In scala we can have fields in interfaces, though internally they are implemented as I explained above (as methods).

Solution 7 - Java

static:

Anything (variable or method) that is static in Java can be invoked as Classname.variablename or Classname.methodname or directly. It is not compulsory to invoke it only by using object name.

In interface, objects cannot be declared and static makes it possible to invoke variables just through class name without the need of object name.

final:

It helps to maintain a constant value for a variable as it can't be overridden in its subclasses.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeakitView Question on Stackoverflow
Solution 1 - JavaAdriaan KosterView Answer on Stackoverflow
Solution 2 - JavaGurpreet singh sidhuuView Answer on Stackoverflow
Solution 3 - JavaJesse GlickView Answer on Stackoverflow
Solution 4 - JavaNawaManView Answer on Stackoverflow
Solution 5 - JavaCarl KlapperView Answer on Stackoverflow
Solution 6 - JavaYaroslavView Answer on Stackoverflow
Solution 7 - JavaSabikaView Answer on Stackoverflow