Java 如何设置接口的类型参数';什么是实现类?
我想知道是否可以将参数的类型设置为实现给定接口的类的类型。看到一些代码,问题会变得更清楚:Java 如何设置接口的类型参数';什么是实现类?,java,Java,我想知道是否可以将参数的类型设置为实现给定接口的类的类型。看到一些代码,问题会变得更清楚: interface A { A sum (???? another); } class AClass implements A { private int internalStuff; A public sum (???? another) { // I want to access another.internalStuff in a type safe fashion
interface A {
A sum (???? another);
}
class AClass implements A {
private int internalStuff;
A public sum (???? another) {
// I want to access another.internalStuff in a type safe fashion
}
}
我当然可以代替????对于类型,在AClass.sum中,将其强制转换为AClass,但这很难看。可以用一些有意义的类型声明来替换“?”吗?Java中没有self类型,因此您需要做一些小技巧来实现这一点 您可以添加一个类型参数,并将递归类型绑定到接口。实现类将此参数设置为自己的类型。像这样:
interface A<T extends A<T>> {
A sum (T another);
}
class AClass implements A<AClass> {
private int internalStuff;
public A sum(AClass another) {
// ....
}
}
接口A{
一笔(T另一笔);
}
类AClass实现了{
私人物品;
公开一笔款项(另一笔){
// ....
}
}
但是,没有什么可以阻止
AClass
执行实现一个
。您必须信任实现类来提供正确的类型参数。您还可以使用带有受保护变量的抽象类