10

How can I declare java interface field that implement class should refine that field ?

for example

public interface IWorkflow{
    public static final String EXAMPLE;// interface field 
    public void reject();
}

// and implement class
public class AbstWorkflow implements IWorkflow
{
    public static final String EXAMPLE = "ABCD"; /*MUST HAVE*/
    public void reject(){}
...
}

Thank you.

nguyên
  • 5,156
  • 5
  • 43
  • 45

2 Answers2

13

You can't.

Also, an interface can't require static methods to be defined on an implementation either.

The best you can do is this:

public interface SomeInterface {
    public String getExample();
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • See this post for more background information: http://stackoverflow.com/questions/512877/why-cant-i-define-a-static-method-in-a-java-interface – Dave Jul 01 '11 at 03:23
4

See section 9.3 of the specification. There is no overriding of fields in interfaces - they are just hidden in some contexts, and ambiguous in others. I'd just stay away. Instead put a getter in the interface (getEXAMPLE())

Ed Staub
  • 15,480
  • 3
  • 61
  • 91
  • 1
    Is is it just me. Doesn't serializable do this? – Link19 Dec 03 '12 at 12:19
  • 2
    @GlenLamb - either I'm not following where you're going, or perhaps you misread the question? – Ed Staub Dec 03 '12 at 16:08
  • Whenever you implement Serializable i'm told that I need to declare a SerializableUID or something. Isn't that what the question is trying to achieve? – Link19 Dec 03 '12 at 16:33
  • 2
    @GlenLamb - Ah, I see. That's a very specific compiler feature - there's nothing, in Serializable.java that drives the warning behavior, which is what nguyên was after. – Ed Staub Dec 03 '12 at 20:04
  • AH, yes that's also what I was after but figured you could do it because of that. Damn. Thanks. – Link19 Dec 04 '12 at 09:51