简体   繁体   中英

Interface with a method that requires parameter of implementation type in signature

Here is an example to clarify what I'm meaning: Let's say I have two classes:

class A {
    boolean isEqual(A instance);
}

and

class B {
    boolean isEqual(B instance);
}

Is there a possibility in Java to define an interface such as

interface I {
    // signature for isEqual(...) here
}

so that the isEqual method in all implementations takes the parameter of the implementation type? Like

class C implements I {
    boolean isEqual(C instance);
}

Thanks in advance!

I think something like this is what you are looking for:

interface Equatable<T> {
    public boolean isEqual(T instance);
}

class C implements Equatable<C> {
    boolean isEqual(C instance);
}

This is similar to the standard Comparable interface.

Is there a possibility in Java to define an interface such as ...

Yes, In generic form:

public interface I<T> {
    public boolean isEqual(T instance);
}

public class C  implements I<C> {

    @Override
    public boolean isEqual(C instance) {
        return false;
    }    
}

Or for example if class A , B and C inherit some super class, lets say DD .

So you can write:

interface I {
   boolean isEqual(<? extends DD> instance);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM