简体   繁体   English

是否可以让方法签名成为它实现的接口的子类型?

[英]Is it possible to have a method signature be a subtype of the interface it implements?

Say I have an interface:假设我有一个界面:

public interface IDto {
}

and a class that implements this interface:和实现此接口的 class :

public class UserProfileResponseDto implements IDto {
}

In another interface I have:在另一个界面中,我有:

public interface ISortingController {
    public List<IDto> findAll();
}

In my concrete controller I have:在我的具体 controller 我有:

public List<UserProfileResponseDto> findAll();

but its telling me that it must be但它告诉我它一定是

public List<IDto> findAll();

Is there a way that would allow public List<UserProfileResponseDto> findAll();有没有办法允许public List<UserProfileResponseDto> findAll(); as it feels like it should be allowed since UserProfileResponseDto implements IDto .因为感觉应该允许,因为UserProfileResponseDto实现IDto The reason I ask this question is because I feel that it gives more verbosity the the controller class, which would make it easier to maintain and operate with.我问这个问题的原因是因为我觉得它让 controller class 更加冗长,这将使其更易于维护和操作。

You need to declare a type parameter in your ISortingController like this:您需要在ISortingController中声明一个类型参数,如下所示:

public interface ISortingController<D extends IDto> {
    public List<D> findAll();
}

and your controller implementation needs to say implements ISortingController< UserProfileResponseDto> .并且您的 controller 实现需要说implements ISortingController< UserProfileResponseDto>

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

相关问题 是否可以在实现接口的 class 中重载方法? - Is it possible to overload a method in a class which implements an Interface? 如何在Java 8编译时确保方法签名“实现”功能接口 - How to ensure at Java 8 compile time that a method signature “implements” a functional interface 如果我在实现该接口的方法中抛出异常,我怎么能不在接口方法签名处抛出异常? - How can I not throw exception at interface method signature If I throw exception in method that implements that interface? Java抽象类实现一个接口,两者具有相同的方法 - Java abstract class implements an interface, both have the same method 类中的静态方法与接口中的默认方法具有相同的签名 - static method in class have same signature as default method in interface 在接口方法中声明子类型捕获 - Declaring subtype captures in an interface method 返回实现接口的方法类型 - Return type of method that implements an interface 如何实现通用接口的方法? - How to implements a method of a generic interface? 接口中方法签名的异常 - Exception in method signature in interface java中是否可以有没有方法的接口 - Is it possible to have an interface without a method in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM