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

7

106

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?

Poky answered 3/10, 2009 at 11:27 Comment(1)
For a note for myself: It's static because the fields of interface won't become a part of the object which implements it.Brockman
C
133

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.

Crumpled answered 3/10, 2009 at 14:32 Comment(5)
It's not necessarily true that final fields are constants; that's only guaranteed for primitive types. In general, the final keyword merely means that the memory location will not change.Plethora
I didn't say final fields are constants, just that constants are final fields. Note that it is allowed to put a non-primitive static final field in an interface. Even though the contents of that field might change, the reference to it is constant.Crumpled
@AdriaanKoster You said exactly that final field is constant: No state is enforced by only allowing constants. - this sentence implies that all final fields are constant. You might try to further argue about words you used, but obviously your statement is at lease misleading.Hemicrania
It must be my waning intellect but after six years of looking at this answer, which happens to be my top scoring answer, I still don't understand the remarks. Please suggest a different wording because I can't see anything wrong.Crumpled
It might have been the intention by the java designers to make an interface stateless, but they failed because an instance field can be a modifiable class. Instead of admitting that they failed, they choose to force instance fields to static final, which is as close to real (real being C/C++) const as you can get in java. Unfortunately this is implicit and may lead to confusion for the non-expert. (I just realized that they are static because I observed unintended behavior. I learned that they are final only from this answer.)Obcordate
P
31

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.

Pomp answered 11/3, 2012 at 17:55 Comment(0)
E
18

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.

Enfield answered 29/10, 2009 at 0:57 Comment(0)
C
9

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.

Cristinacristine answered 3/10, 2009 at 11:36 Comment(3)
NawMan, your explanation about "The felds must be static..." does not make much sense. But you were very right abt the "The fields must be final..."Poky
I don't think he is right about the reason why the fields must be final. Allowing different implementers to change a field is not problematic, since otherwise inheritance would be problematic. Fields must be final, as Adriaan said, because an interface is, and should, be stateless. An interface with a state basically should be an abstract class.Haplosis
If you have a public static field that is not final, findbugs will complain (rightly!).Silver
B
2

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";
    ...
}
Blackmail answered 3/4, 2014 at 19:13 Comment(1)
You seem to be complaining more about the fields being static than being final.Overblouse
H
0

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).

Husain answered 4/10, 2016 at 7:37 Comment(0)
S
-2

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.

Sophisticated answered 2/11, 2016 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.