17

Specification states that interface is intended to define the contract for what a class can do and contains a set of methods required to implement. But at the same time, interface may have constants.

For what purpose it is allowed in Java?

What is the point of existence of constants in interface and how can they be used in it? As I understand they can only be taken as arguments by methods. But I do not see much point because interface doesn't say anything about how a class will implement its methods.

4
  • they can be used as a sort of global variables
    – DPM
    Jun 1, 2013 at 16:13
  • 5
    Good question... Actually, since the introduction of enums in Java 5, there is absolutely no point at all AFAICT.
    – fge
    Jun 1, 2013 at 16:14
  • E.g. when the interface implements a setFlags() method and these flags (and their numerical values) are predefined by the interface (by the documentation of the interface) Jun 1, 2013 at 16:15
  • They are very useful with you need constants in subclasses, for example if you have an interface that defines an http request it may be useful to define constants for GET and POST etc. Having said that, be very wary of the Constant Interface Antipattern. Jun 1, 2013 at 16:16

7 Answers 7

11

A constant is part of an interface, too. Constant values are used in design to avoid Magic Numbers, i.e. numbers which have a certain meaning to the implementation, but seem to pop out of nowhere.

There are many cases where numerical values influence the behavior of the code. Consider, for example, an interface for a GUI button. How this button is actually drawn is up to the implementation; but what kind of button it is is part of the contract which forms the interface: Is it a normal push button, has it an image, or is it a checkbox? This behavior can be modified using constants, commonly used by OR'ing values: For example, int buttonType = PUSHBUTTON|IMAGEBUTTON.

7
  • 2
    Note that (since Java 5) an interface can also declare an enum which is usually more fit for behavior modifying since it disallows any non-declared options and is typesafe. A method (even internal) is much more readable if it's setButtonType(EnumSet<ButtonType> types) that the constant approach setButtonType(int typesMask). Jun 1, 2013 at 16:23
  • 2
    Enums usually don't come handy for configuration keys. For example when you want to retrieve a special property from a properties file. Those are usually strings, so the detour over enums isn't used. Jun 1, 2013 at 16:57
  • 1
    @ThomasJungblut In that case, you should store the name() of the enum and then invoke YourEnum.valueOf(valFromProperties). Or try some ordinal() handling, but that's probably far worse if you're not super careful. Anyway, let's not fall into arguing here, both your and mine approaches have their pros and cons and everyone can decide which way to go. Jun 1, 2013 at 17:05
  • @Slanec They have dots in their names by convention, so it isn't syntactically possible. You can add a string field to the enum though. But that's what I meant by detour- should just be an addition. Jun 1, 2013 at 17:08
  • 1
    of course enums have no dots in it. I meant the property keys. E.G. see the configurations of Hadoop or other Apache projects. Jun 1, 2013 at 17:20
2

The constants can be used outside the interface.

For example, they can be used by the classes that implement the interface. This may be useful if a single definition is required across implementation classes.

For example, consider an interface that defines some bitwise-OR style constants that may be used consistently across all the subclasses. Only a single definition of these is required, and only a single set need be learned.

2
  • I understand that it is possible, but I don't understand for what purpose. After all, this is somewhat the imposing implementation by interface.
    – Alex
    Jun 1, 2013 at 16:17
  • A constant value is data, separate from implementation. Adding an example. Jun 1, 2013 at 16:19
2

Imagine an application that uses resources such as images or sounds. You may define a common interface for your resources.

interface MyResource {
    void load();
    void dispose();
    // ...
}

Your folder structure may look like the following:

+ Root
|--+ Resources
   |--+ Images
   |--+ Sounds
   |--+ Data

You know that all your resources will be under Root/Resources/. This information can be shared and known, not only by your resources, but also by your other application components.

Having this in mind, your interface now becomes:

interface MyResource {
    public static final String RESOURCE_ROOT_PATH = "Root/Resources/";

    void load();
    void dispose();
    // ...
}

Your specific implementations, such as an image, may define their own root path, based on the common path for all resources.

class MyImage implements MyResource {
    public static final String IMAGE_ROOT_PATH =
            MyResource.RESOURCE_ROOT_PATH + "Images/";

        ...
}

Alternatively, you may look at interfaces like javax.swing.SwingConstants, which are used to share constants for a certain functionality among implementations.

But, then again, for this sort of thing, I'd rather use an enum, nowadays.

1

Lets' explain with an example:

public interface People {
    /**
     * Gets the population for the given type
     */
    public Population getPopulationForType(int populationType);
}

Do you find the above contract easy to understand? Or wouldn't the following be better?

public interface People {
    int BLACK_POPULATION_TYPE = 0;
    int ASIAN_POPULATION_TYPE = 1;
    int WHITE_POPULATION_TYPE = 2;

    /**
     * Gets the population for the given type
     */
    public Population getPopulationForType(int populationType);
}

You could have a FrenchPeople, AmericanPeople and ChinesePeople implementation, but all are supposed to return the popuation for all three possible types of people.

3
  • 3
    This isn't a good example, an enum would be a much nicer fit here. Jun 1, 2013 at 16:18
  • enums were introduced in Java 5. Interfaces were introduced in Java 1.0. Similar use cases can be imagined, where an enum would make less sense. You could use bitmasks, for example.
    – JB Nizet
    Jun 1, 2013 at 16:20
  • Sure, pre-Java 5, interface constants for this type of usage make a lot of sense. If we're talking post-Java 5, then instead of bitmasks, an EnumSet should be the preferred choice (Effective Java, 2nd ed., Item 32). Jun 1, 2013 at 16:56
1

One of the usages of such constants to me post-Java 5 (which brought enums that are superior to bitmasking and can be declared on interfaces as well) is when the constant is a part of the method's contract.

Consider an interface like this:

public interface Element {
    Element NONE = new EmptyElement();

    /**
     *  Looks up an element using this element as a root.
     *  If the lookup fails, returns Element.NONE.
     */
    Element findElements(String searchBy);
}

The constant is a part of the method's contract and should, I think, be therefore in the interface. This is useful in API programming since you can offer default or special return values for the API methods for everyone to use and check against.

The most common case of this prevents the problems with ambiguous null values returned (e.g. the HashMap#get() method will return null both for a missing key and for a null value), but there is much more to it than just nulls - any special values that can be returned should be, I think, on the interface.

0

One possible use of interface constants is to make sure that the constants are visible across all implementation classes. Sure, you can put all those in a class and use the same class in those implementation classes but it's much easier to define the constants at the specification level.

Think of it this way; even though the constants don't define the "implementation", they are there in case any implementation needs them.

0

They can be used to give symbolic meaning to the return args/input args of the methods. It has been so pre-enum days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.