Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fields in interfaces

I have a basic question in Java, but it's a general question in OOP. Why do interfaces allow fields to be set? Doesn't that run contrary to what an interface is supposed to do?

The way I made sense of it, an interface is what in English would be an adjective. So, if my class implements the interfaces Runnable and Serializable, I'm ensuring the user that my class will satisfy the conditions to be Runnable and Seriablizable. However, that would mean interfaces are "stateless", but they are allowed to have fields in Java...

Am I missing something?

like image 402
Sal Avatar asked Feb 25 '12 18:02

Sal


People also ask

Can you have fields in an interface?

An interface can't contain instance fields, instance constructors, or finalizers. Interface members are public by default, and you can explicitly specify accessibility modifiers, such as public , protected , internal , private , protected internal , or private protected .

Can you have fields in interfaces Java?

A Java interface is a bit like a Java class, except a Java interface can only contain method signatures and fields. A Java interface is not intended to contain implementations of the methods, only the signature (name, parameters and exceptions) of the method.

WHY CAN interfaces have fields?

Interfaces don't contain fields because fields represent a specific implementation of data representation, and exposing them would break encapsulation. Thus having an interface with a field would effectively be coding to an implementation instead of an interface, which is a curious paradox for an interface to have!

Are all fields in interface static and final?

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.


1 Answers

All fields in interface are public static final, i.e. they are constants.

It is generally recommended to avoid such interfaces, but sometimes you can find an interface that has no methods and is used only to contain list of constant values.

like image 117
Andrew Logvinov Avatar answered Oct 09 '22 03:10

Andrew Logvinov