Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a class implement a constants-only interface?

Tags:

java

Today I looked at the ZipEntry class and found the following:

public class ZipEntry implements ZipConstants, Cloneable

ZipConstants does not define any methods - only constants (static final int LOCHDR = 30)

It then occurred to me that implementing the interface with constants lets you access those constants directly, as if they were defined in the class itself. For example:

public interface Constants {
    static final int CONST = 2;
}

public class implements Constants {
    int doSomething(int input) {
        return CONST * input;
    }
}

Is there another reason not to use this, apart from:

  • it is at first confusing where the constant is coming from
  • it is considered wrong to use interfaces for constants definition

I'm curious because it is definitely not a very common practice.

like image 922
Bozho Avatar asked Jan 14 '10 10:01

Bozho


1 Answers

Another reasons not to use this:

Since Java 5, there is a "clean" language feature that achieves the same goal: static imports.

Implementing interfaces to use constants is basically a pre-Java-5 hack to simulate static imports.

like image 184
Michael Borgwardt Avatar answered Sep 28 '22 01:09

Michael Borgwardt