Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I declare java interface field that implement class should refine that field

Tags:

java

interface

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.

like image 853
nguyên Avatar asked Jul 01 '11 03:07

nguyên


People also ask

Can we declare fields in interface in Java?

Yes, you can have constant fields in interfaces, but you are right when you say that "it seems contrary to what an interface is supposed to do", as it is not a good practice.

Can you declare fields in an interface?

We can declare constant fields in an interface as follows. It declares an interface named Choices, which has declarations of two fields: YES and NO. Both are of int data type. All fields in an interface are implicitly public, static, and final.

How do you declare an interface in Java?

An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction.

How do you implement an interface to a class?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.


2 Answers

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();
}
like image 161
Bohemian Avatar answered Oct 23 '22 03:10

Bohemian


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())

like image 36
Ed Staub Avatar answered Oct 23 '22 02:10

Ed Staub