如果扩展了抽象方法中使用的参数的类,则覆盖方法中的参数的类 [英] Override class of parameter in method if it extends that of parameter used in abstract method

查看:130
本文介绍了如果扩展了抽象方法中使用的参数的类,则覆盖方法中的参数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下四个类,其中两个是抽象类,两个是具体类:Abstract1Concrete1Abstract2Concrete2.

Suppose I have the following four classess, out of which two are abstract and two are concrete: Abstract1, Concrete1, Abstract2, Concrete2.

Concrete1扩展Abstract1Concrete2扩展Abstract2.

假设我有以下四个类,其中两个是抽象类,两个是具体类:AbstractPropConcretePropAbstractClassConcreteClass.

Suppose I have the following four classess, out of which two are abstract and two are concrete: AbstractProp, ConcreteProp, AbstractClass, ConcreteClass.

ConcreteProp扩展AbstractPropConcreteClass扩展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()中参数的类(AbstractPropConcreteProp)不同,从而使@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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆