如果扩展了抽象方法中使用的参数的类,则覆盖方法中的参数的类 [英] Override class of parameter in method if it extends that of parameter used in abstract method
问题描述
假设我有以下四个类,其中两个是抽象类,两个是具体类:Abstract1
,Concrete1
,Abstract2
,Concrete2
.
Suppose I have the following four classess, out of which two are abstract and two are concrete: Abstract1
, Concrete1
, Abstract2
, Concrete2
.
Concrete1
扩展Abstract1
,Concrete2
扩展Abstract2
.
假设我有以下四个类,其中两个是抽象类,两个是具体类:AbstractProp
,ConcreteProp
,AbstractClass
,ConcreteClass
.
Suppose I have the following four classess, out of which two are abstract and two are concrete: AbstractProp
, ConcreteProp
, AbstractClass
, ConcreteClass
.
ConcreteProp
扩展AbstractProp
,ConcreteClass
扩展AbstractClass
.
AbstractClass
的代码如下所示:
public abstract class AbstractClass {
protected AbstractProp someProperty;
public abstract void setProperty(AbstractProp someProperty);
}
实现ConcreteClass
时,我希望能够做这样的事情(请记住AbstractProp
扩展了`ConcreteProp):
When implementing ConcreteClass
, I want to be able to do something like this (keep in mind that AbstractProp
extends `ConcreteProp):
public class ConcreteClass extends AbstractClass {
@Override
public void setProperty(ConcreteProp someProperty) {
this.someProperty = someProperty;
}
}
但是最后一段代码无效,因为setProperty()
中参数的类(AbstractProp
和ConcreteProp
)不同,从而使@Override
注释无效.有没有办法可以使用仿制药和/或通配符来完成我要在这里完成的工作?
But this last bit of code isn't valid because the classes of the parameters (AbstractProp
and ConcreteProp
) in setProperty()
differ, making the @Override
annotation invalid. Is there a way I can accomplish what I'm trying to do here, perhaps using generics and/or wildcards?
注意::我知道这种命名方式是不好的做法,并且代码过于简单化,我实际上并没有使用它,这只是一个使问题尽可能简单的示例可能.
NOTE: I'm aware that this type of naming is bad practice and the code is oversimplistic, I'm not actually using it and this is just an example to keep the question as simple as possible.
推荐答案
如果在AbstractClass
上引入泛型,则可以实现您所要求的.
If you introduce generics on the AbstractClass
you can achieve what you are requesting.
public abstract class AbstractClass<T extends AbstractProp> {
protected T someProperty;
public void setProperty(T someProperty) {
this.someProperty = someProperty;
}
}
,然后在ConcreteClass
中指定要让ConcreteProp
成为您想要的类型.
And then specify that you want ConcreteProp
to be the type you want in your ConcreteClass
.
public class ConcreteClass extends AbstractClass<ConcreteProp> {
@Override
public void setProperty(final ConcreteProp someProperty) {
this.someProperty = someProperty;
}
}
这篇关于如果扩展了抽象方法中使用的参数的类,则覆盖方法中的参数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!