Shreyos Adikari
Shreyos Adikari

Reputation: 12744

Public static final declaration of an instance variables in JAVA Interfaces

Why we use public static final declaration of instance variables in a Java Interface?
All the variables are implicitly public static final in a Java Interface.
Is it a good coding practice to use public static final in constant variable although it is declared inside an Interface.

For example :

public interface TestInterface{

public static final String EX_CONSTANT = "ABC";
public static final int EX_INT_CONSTANT = 5;
public static final double EX_DOUBLE = 5.0;
public static final Integer EX_INTEGER = 10;

}

Upvotes: 10

Views: 21191

Answers (7)

Batakj
Batakj

Reputation: 12743

From the book Effective java by JOshua Bloch

Item 19: Use interfaces only to define types

When a class implements an interface, the interface serves as a type that can be used to refer to instances of the class. That a class implements an interface should therefore say something about what a client can do with instances of the class. It is inappropriate to define an interface for any other purpose.

One kind of interface that fails this test is the so-called constant interface. Such an interface contains no methods; it consists solely of static final fields, each exporting a constant. Classes using these constants implement the interface to avoid the need to qualify constant names with a class name. Here is an example:

// Constant interface antipattern - do not use!
public interface PhysicalConstants {
    // Avogadro's number (1/mol)
    static final double AVOGADROS_NUMBER = 6.02214199e23;
    // Boltzmann constant (J/K)
    static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
    // Mass of the electron (kg)
    static final double ELECTRON_MASS = 9.10938188e-31;
}

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.

There are several constant interfaces in the Java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.

If you want to export constants, there are several reasonable choices. If the constants are strongly tied to an existing class or interface, you should add them to the class or interface. For example, all of the boxed numerical primitive classes, such as Integer and Double, export MIN_VALUE and MAX_VALUE constants. If the constants are best viewed as members of an enumerated type, you should export them with an enum type (Item 30). Otherwise, you should export the constants with a noninstantiable utility class (Item 4). Here is a utility class version of the PhysicalConstants example above:

// Constant utility class
package com.effectivejava.science;

public class PhysicalConstants {
    private PhysicalConstants() {
    } // Prevents instantiation

    public static final double AVOGADROS_NUMBER = 6.02214199e23;
    public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
    public static final double ELECTRON_MASS = 9.10938188e-31;
}

Normally a utility class requires clients to qualify constant names with a class name, for example, PhysicalConstants.AVOGADROS_NUMBER. If you make heavy use of the constants exported by a utility class, you can avoid the need for qualifying the constants with the class name by making use of the static import facility, introduced in release 1.5:

// Use of static import to avoid qualifying constants
import static com.effectivejava.science.PhysicalConstants.*;
public class Test {
    double atoms(double mols) {
        return AVOGADROS_NUMBER * mols;
    }
...
// Many more uses of PhysicalConstants justify static import
}

In summary, interfaces should be used only to define types. They should not be used to export constants.

Upvotes: 4

user207421
user207421

Reputation: 310884

You are correct: it is redundant. I don't like to add redundant syntax at any time. However the practice does has its adherents. Some also like to add parentheses around return-expressions, on the fallacious grounds that it's like an 'if' statement; extra parentheses to 'clarify' arithmetic expressions that a third-grader would understand; etc. It's all part of the rich tapestry of life.

Upvotes: 1

Carlos Cambón
Carlos Cambón

Reputation: 112

When you are working in a team of programmers, you will find junior programmers who do not know the fact that by default the variables are public static final in the interface, and seeing the variables declared that way will give them extra information about the interface and the use of its variables.

Upvotes: 2

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

IMO, Interface is a contract. Once variables are declared or defined they are not going to change. That's why generally we make them public static final.

Readability is another factor which makes declaration redundant.

Upvotes: 3

axtavt
axtavt

Reputation: 242686

Use of uniform syntax in both classes and interfaces simplifies refactoring.

You may want to turn your interface into a class somewhere in future, or move these fields into a class, and you'll get a semantical difference if you overlook some fields defined without public static final (of course, we have tools for refactoring, but nonetheless).

I think it's the same thing as support of @Overriden annotation for implementations of methods declared in interfaces that was introduced in Java 6 - it's redundant in its current form, but may become useful in case of refactoring.

Upvotes: 11

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

I don't think so. All interface variables are implicitly public static final so no meaning to mark them same.

Upvotes: 5

Brian
Brian

Reputation: 17309

Admittedly, it's redundant. Usually people just don't know that they're implicitly public static final and declare it anyway. Ditto with things like declaring:

public abstract interface Test { // Interfaces are always abstract
    public void testMethod(); // Interface methods are always public
    abstract void anotherTestMethod(); // Also redundant
}

Usually it just boils down to the fact that people don't know that they don't have to declare it one way or the other. I once talked to someone (who was a seasoned programmer) that thought the default case in switch is required or it won't compile.

That being said, the only argument to be made for adding them is that they clarify what their actual visibility and whatnot actually is. It's a matter of readability and clarification, and whether or note to include them is irrelevant in terms of how it actually behaves.

Upvotes: 2

Related Questions