Java interface with fields

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?

In c#, you can use an interface to implement a property, which behaves similar to a getter/setter method in java, but is frequently treated like a class member.

5 Answers 5

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.

Answering for , «Why would you say that interfaces with constants are avoided» , because designwise its not good practise, if you want to define constants, simply create an Enum class and define them there, its more logical and neat. In my opinion it does not make sense to implement an interface to make use of the constants, thats bloated code.

@MuhammedOzdogan , you can see item 22: «Use interfaces only to define types» of «Effective Java» : «The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API.»

First of all, there’s difference between OOP paradigm and OOP implementation in Java, so same words may mean a bit different things.

Читайте также:  Spinning an image in html

In OOP the paradigm interface is what you can do with the object (or what object can do for you). Any object can have several interfaces and thus play different roles. For example, someone may work as a programmer and be able to create programs, but at the same time he may be a husband and father and thus be able to pay the bills for his family and take care of children. Here «programmer», «husband» and «father» are interfaces, and a person is an object that implements them. Note, that interfaces do not imply presence of any specific features (fields) for implementing object, just actions that this object should be able to perform.

Java more or less follows this idea, but as any paradigm implementation has its own features. Java allows describing methods, that is actions that the implementing object should be able to perform, but not any implementation details, thus, nothing about object fields or private methods.

But what about constants ( public final static fields)? Are they part of implementation or interface. It could be both. E.g. interface «programmer» can have constant WORK_HOURS set to «8». Thus Java allows you to describe constants in interfaces too.

Note, that Java only helps you to make good OOP design, but it doesn’t strongly require it. In particular, not all public methods of an object should exist in interface too. For example, getter and setter methods are normally public, but in fact they are the part of implementation, not interface, and thus it’s worth not to bring them into interface.

(Please also note, that most things I described here are about mainstream OOP like in Java, but there are also other kinds of OOP such as prototype-based one, in particular implemented in JavaScript).

Источник

Interfaces with static fields in java for sharing ‘constants’

I’m looking at some open source Java projects to get into Java and notice a lot of them have some sort of ‘constants’ interface. For instance, processing.org has an interface called PConstants.java, and most other core classes implement this interface. The interface is riddled with static members. Is there a reason for this approach, or is this considered bad practice? Why not use enums where it makes sense, or a static class? I find it strange to use an interface to allow for some sort of pseudo ‘global variables’.

public interface PConstants < // LOTS OF static fields. static public final int SHINE = 31; // emissive (by default kept black) static public final int ER = 32; static public final int EG = 33; static public final int EB = 34; // has this vertex been lit yet static public final int BEEN_LIT = 35; static public final int VERTEX_FIELD_COUNT = 36; // renderers known to processing.core static final String P2D = "processing.core.PGraphics2D"; static final String P3D = "processing.core.PGraphics3D"; static final String JAVA2D = "processing.core.PGraphicsJava2D"; static final String OPENGL = "processing.opengl.PGraphicsOpenGL"; static final String PDF = "processing.pdf.PGraphicsPDF"; static final String DXF = "processing.dxf.RawDXF"; // platform IDs for PApplet.platform static final int OTHER = 0; static final int WINDOWS = 1; static final int MACOSX = 2; static final int LINUX = 3; static final String[] platformNames = < "other", "windows", "macosx", "linux" >; // and on and on > 

Also note that platformNames may be public , static and final , but it is definitely not a constant. The only constant array is one with zero length.

Читайте также:  Пример веб-страницы с php кодом

@ThomasW I know this is a few years old, but I needed to point out an error in your comment. static final is not necessarily redundant. A class or interface field with only the final keyword would create separate instances of that field as you create objects of the class or interface. Using static final would make each object share a memory location for that field. In other words, if a class MyClass had a field final String str = «Hello»; , for N instances of MyClass, there would be N instances of the field str in memory. Adding the static keyword would result in only 1 instance.

@Sintrias that’s the case for classes but not interfaces. In an interface any field declared is implicitly static.

@awgtek Thanks for the correction. I misunderstood ThomasW’s comment and didn’t know that’s how interfaces work in Java.

8 Answers 8

It’s generally considered bad practice. The problem is that the constants are part of the public «interface» (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all «re-export» all of its constants (even the ones that they don’t use) as their own.

But don’t just take my word for it, Josh Bloch also says it’s bad:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.

Читайте также:  Stop python script console

Источник

Оцените статью