简体   繁体   English

Java方法从继承返回类型

[英]Java Method return Types from Inheritance

I'm writing a method in a class Parent that returns a set of some object A . 我正在类Parent中编写一个方法,它返回一组对象A However, I have a class Child (inheriting form Parent ). 但是,我有一个类Child (继承Parent )。 I want it to return a set of some object B ( B inheriting from A ). 我希望它返回一组对象BB继承自A )。

More specifically, my methods looks something like this (it throws compile errors right now). 更具体地说,我的方法看起来像这样(它现在抛出编译错误)。

Parent class method: Parent类方法:

public abstract <T extends A> Set<T> getSet();

Child class (extends Parent class) method: Child类(扩展Parent类)方法:

public <T extends B> Set<T> getSet() {...}

Is it possible to do this, or does it not make sense? 有可能做到这一点,还是没有意义?

First of all, let me explain why your code does not compile. 首先,让我解释一下为什么你的代码不能编译。 Basically, if you have class A {} and class B extends A {} then Set<B> is not a sub-type of Set<A> . 基本上,如果你有class A {} class B extends A {}那么Set<B> 不是 Set<A>的子类型。 So if your parent method returns a Set<A> , your override must return the same thing. 因此,如果您的父方法返回Set<A> ,则您的覆盖必须返回相同的内容。 A Set<B> is a completely different type . Set<B>完全不同的类型

Likewise, Set<T extends B> is not a sub-type of Set<T extends A> . 同样, Set<T extends B>不是Set<T extends A>的子类型。 The full explanation is found in Java docs . Java文档中提供了完整的说明。

The closest solution that I can think of, uses wildcards: 我能想到的最接近的解决方案是使用通配符:

class A {}

class B extends A {}

abstract class Parent {
    abstract Set<? extends A> getSet();
}

class Child extends Parent {
    Set<? extends B> getSet() {
        return new HashSet<B>();
    }
}

Set<? extends B> Set<? extends B> is a sub-type of Set<? extends A> Set<? extends B> Set<? extends A>的子类型Set<? extends A> Set<? extends A> , and this now works because of covariant return types (appreciate the comments from Lii & Marco13 below). Set<? extends A> ,现在这是因为协变返回类型 (感谢下面的Lii和Marco13的评论)。

Depending on what you are trying to achieve exactly, this might be more limited than you expect, but is probably as close as it gets. 根据您想要达到的目标,这可能比您预期的更有限,但可能会尽可能接近。

Perhaps something similar could be achieved using inner classes, as Jude said, but I don't see how that would be a more convenient solution. 正如Jude所说,也许使用内部类可以实现类似的东西,但我不知道这将是一个更方便的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM