0

I want to be able to do something akin to the following

public interface myInterface{
    public final String MY_CONST
}

public class myImpl implements myInterface{
     MY_CONST="Hello World"
}

Basically, I want to declare a constant in my interface, and define it in my implementation. Is there a way to do something like this in java/groovy?

Steve
  • 4,457
  • 12
  • 48
  • 89
  • 5
    No. And anyway, [*the constant interface pattern is a poor use of interfaces*](http://stackoverflow.com/a/2659740/1225328). – sp00m Feb 07 '17 at 14:45
  • 1
    No. All fields in Java interfaces are implicitly `static` and `final`, the latter preventing assignment delegation to implementing classes. – Mena Feb 07 '17 at 14:45

2 Answers2

7

In Java, the closest you can come is a getter:

public interface myInterface{
    String getConstant();
}

public class myImpl implements myInterface{
     public String getConstant() {
        return "Hellow world";
     }
}

...since interfaces can't have instance fields.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • You should maybe declare `getConstant()` final in the child class otherwise it could be overrided. – davidxxx Feb 07 '17 at 14:52
  • @davidxxx: Well, if the value isn't defined by the interface, it's not clear whether it's a problem or a goal that it can be overridden in a subclass. – T.J. Crowder Feb 07 '17 at 15:50
  • I agree with it is not clear but If it is a goal that the value to be redefined (so more than once), the need has not really relation with the constant concept. – davidxxx Feb 07 '17 at 16:53
1

You can use traits in Groovy with similar effect:

trait WithConstant {
    final String VALUE = "tim"
}

class MyClass implements WithConstant {
    final String VALUE = "steve"

    def print() {
        println VALUE
    }
}

new MyClass().print()
tim_yates
  • 167,322
  • 27
  • 342
  • 338