I want to use an interface like this :
public interface ResultItem {
public int getConfidence();
public boolean equals(ResultItem item);
public ResultItem cloneWithConfidence(int newConfidence);
}
I have it implemented by different kind of objects representing a voice recognition result.
The idea is, I wish to compare only results of the same kind. That is, if I create a class IntResult
implementing ResultItem
, I want that the method signatures become :
public boolean equals(IntResult item);
public IntResult cloneWithConfidence(int newConfidence);
I feel that there is a design flaw in my interface, because for now I am using pretty ugly casts on the results of cloneWithConfidence and of other methods returning a ResultItem.
Is there a better way?
In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.
Interface types act like class types. You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type.
An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.
There is a frequently-seen idiom that goes as follows:
public interface ResultItem<T extends ResultItem<T>> {
public int getConfidence();
public boolean equals(T item);
public T cloneWithConfidence(int newConfidence);
}
public class IntResult implements ResultItem<IntResult> {
//...
}
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