Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 760
peakit Avatar asked Oct 03 '09 11:10

peakit


People also ask

Are all fields in interface static and final?

It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Why are all fields of interface final?

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. If you have a public static field that is not final , findbugs will complain (rightly!).

Are data fields declared in an interface are implicitly public static and final?

An interface can have default methods and static methods. Any other methods are implicitly public and abstract. All the fields declared in an interface are implicitly public, static and final constants.

Are fields in an interface final?

All the fields of an interface are public, static and, final by default.


1 Answers

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.

like image 132
Adriaan Koster Avatar answered Sep 23 '22 00:09

Adriaan Koster