简体   繁体   English

与需要签名中实现类型的参数的方法进行接口

[英]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 Java是否有可能定义一个接口,例如

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

so that the isEqual method in all implementations takes the parameter of the implementation type? 以便所有实现中的isEqual方法都采用实现类型的参数? 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. 这类似于标准的Comparable接口。

Is there a possibility in Java to define an interface such as ... Java是否有可能定义诸如...的接口

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 . 又例如,如果类ABC继承了某些超类,则可以说DD

So you can write: 所以你可以这样写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 接口如何包含在其签名或返回类型中引用接口的具体实现类型的方法? - How can an interface include a method that references the concrete implementation type of the interface in its signature or return type? 在接口中使用Java泛型来强制实现具有实现类型作为参数的方法 - Using Java generics in an interface to enforce implementation of a method with the implementing type as a parameter 接口和实现签名不匹配 - Mismatched interface and implementation signature Java:获取带有接口参数的方法及其实现 - Java: Get method with interface parameter with its implementation 将类型参数传递给接口方法 - Pass type parameter to method of interface 为具有泛型参数的java接口方法使用特定的实现类型。 如何避免不熟练的演员 - Using specific implementation type for a java interface method having generics parameter. How to avoid uncheked cast 使用包含非导出参数类型的方法的接口实现(Java 9模块) - Interface implementation with a method containing a non-exported parameter type (Java 9 modules) 具有实现特定参数类型的模板方法模式 - Template method pattern with implementation specific parameter type 参数类型与声明类型相同的接口方法 - Interface method with parameter of same interface type as declaring type 接口中方法签名的异常 - Exception in method signature in interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM