Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an interface instance method accept arguments of the same class only?

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?

like image 571
Dunaril Avatar asked Mar 01 '11 16:03

Dunaril


People also ask

How do you call an interface method in the same class?

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.

Can interface method have arguments?

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.

Can an interface be an instance of a class?

An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.

Can we make an instance of an 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”.


1 Answers

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> {
  //...
}
like image 117
NPE Avatar answered Sep 23 '22 05:09

NPE