我有这段代码可以工作:
接口:
public interface Queries<T> {
List<User> runQuery(T query);
}
并使用界面:
public class UserQueries implements Queries<UserQuery> {
@Override
List<User> runQuery(UserQuery q){
}
}
我想用以下代码替换上面的代码,但是,它不起作用:
新介面:
public interface Queries {
// I want to pass the type parameter within the abstract method instead of the using Queries<T>
<T> List<User> runQuery(T query);
}
并使用新的界面(版本2):
public class UserQueries implements Queries {
// does not work, compiler complains:
// "The method runQuery(UserQuery) of type UserQueries must override or implement a supertype method
@Override
List<User> runQuery(UserQuery q) {
}
}
如何<T>
在类的方法接口中使用类型参数?
您正在尝试混合使用两个概念,一个是泛型,另一个是继承。
版本1在版本1中,您具有通用接口
public interface Queries<T>
在实现中,您限制它接受UserQuery
类型
public class UserQueries implements Queries<UserQuery> {
版本2在版本2中,您具有使用通用抽象方法的具体接口
public interface Queries {
// I want to pass the type parameter within the abstract method instead of the using Queries<T>
<T> List<User> runQuery(T query);
}
因此,如果您实现Queries
接口,则必须提供所有抽象方法的实现(如果更改方法的签名或方法的语法,则该方法在类中被视为不同的方法,而在接口中则被视为抽象方法)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句