从父项继承特定于子项的方法 [英] Inheriting child-specific method from parent

查看:106
本文介绍了从父项继承特定于子项的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否可能,但我想到了Java中的某些东西:

I don't know if this is at all possible, but I was thinking of something in Java:

如果我有一个抽象的父类,我可以做这:

If I have an abstract parent class, I can do this:

public ParentClass add(ParentClass a, ParentClass b);

如果 ParentClass 然后有一个孩子和我要重写此方法,子类仍然有一个 ParentClass add(ParentClass,ParentClass)方法。

If ParentClass then has a child and I want to override this method, the child class will still have a ParentClass add(ParentClass, ParentClass) method.

有没有办法使父函数派生自己的每个孩子?

我不知道我的措辞是正确的,但是这样的事情:

Is there a way to make the parent function derive itself to each child?
I don't know if I'm wording it right, but something like this:

// ParentClass.java
public ParentClass add(ParentClass a, ParentClass b);

// Foo.java
@Override // or an equivalent
public Foo add(Foo a, Foo b) {}

// Bar.java
@Override
public Bar add(Bar a, Bar b) {}

注意每个孩子 都没有 ParentClass add(...)函数,而是每个孩子都有一个而不是类型?

Notice how each child doesn't have a ParentClass add(...) function, but rather one for each of their own types instead?

很明显,我可以自己做这些,但我希望能够在父母中创建可覆盖的类别。我从来没有在练习中见过这个,所以我怀疑它的存在。我只想澄清一个人比我更高的Java知识。谢谢。

Obviously I can just make these myself, but I want to be able to create overridable ones in parents. I've never seen this in practice before, so I doubt its existence. I just want to clarify with someone with a higher Java knowledge than me. Thanks.

从理论上讲,我认为没有语言做过,像这样:

In theory, which I guess no language has ever done, something like this:

public child add(child a, child b);
// where *child* is the type of the child inheriting the method


推荐答案

在Java中,不允许使用方法参数的协方差。

继承方法: public ParentClass add(ParentClass a,ParentClass b);
对于所有的孩子是合法的,因为它可以指定ParentClass的任何子类作为参数。

它更灵活。

现在,如果你不希望这种灵活性,你想强制继承方法中的参数的特定类型,你应该使用一个泛型抽象类。

In Java covariance of parameters of a method is not allowed.
This inherited method : public ParentClass add(ParentClass a, ParentClass b); is legal for all children as it will allow to specify any subclass of ParentClass as parameters.
It is more flexible.
Now, if you don't want this flexibility and you want to force a specific type for parameters in the inherited method, you should use a generics abstract class.

public abstract class ParentClass <T extends ParentClass <?>>{
    public abstract ParentClass<?> add(T a, T b);
}

在子类中,您可以编写:

And in child class you could write :

public class ChildClass extends ParentClass <ChildClass>{
    public ParentClass<?> add(ChildClass a, ChildClass b){
       ....
   }
}

这篇关于从父项继承特定于子项的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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