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.
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.
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.
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.
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.
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();
}
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With