gpt4 book ai didi

Java 泛型 : Generic parameter defined at method level vs interface level

转载 作者:行者123 更新时间:2023-12-03 23:00:54 24 4
gpt4 key购买 nike

我遇到以下与泛型有关的问题。我有以下内容:

接口(interface)A为:

public interface InterfaceA {
public <T extends DTOInterface> Object methodName (T dto) {}
}

DTOInterface 只是一个空接口(interface)。

那么我的实现将是:

public class ImplementationA implements InterfaceA {
public Object methodName(DTOImplementation dto) {
return null;
}
}

DTOImplementation 只是一个实现 DTOInterface 的类。

这是失败的,因为 ImplementationA 中的方法未被识别为 InterfaceA 中方法的有效实现。

但是,如果我在接口(interface)级别定义参数,即

public interface InterfaceA **<T extends DTOInterface>** {
public Object methodName (T dto) {}
}

然后将实现定义为:

public class ImplementationA implements **InterfaceA<DTOImplementation>** {
public Object methodName(DTOImplementation dto) {
return null;
}
}

它确实有效。该方法被认为是有效的实现。

有人知道为什么会这样吗?

最佳答案

第一个声明说,为了实现 InterfaceA,子类需要提供一个方法 methodName,它适用于任何类型 T扩展方法调用者选择的 DTOInterface 。也就是说,TmethodName的调用者可以选择的参数;实现 InterfaceA 的类无法选择它。因此,当您提供的实现试图为 methodName 选择特定的 T 值并且仅实现该值时,编译器会拒绝您的程序。

另一方面,第二个声明是一个接口(interface),它允许实现者为 T 提供一个特定的值,并且只为那个特定的选择实现它的方法。 ImplementationA 选择只为 DTOInterface 的一个特定子类型(即 DTOImplementation)实现 InterfaceA,并且只提供一个方法对于 T 的选择。这很好。

关于Java 泛型 : Generic parameter defined at method level vs interface level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19179984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com