java对来自同一基类的不同对象进行迭代
我有不同的课程来定义一段音乐的结构元素。层次结构是Song
>Section
>CompositeMusic
>MusicTime
,所有这些都继承自一个抽象MusicComponent
类
MusicTime
是最底层,它知道播放哪个Chord
以及有多少个胯部,并且包含在CompositeMusic
对象的条中Section
反过来持有CompositeMusics
并允许节奏和时间特征的变化
我需要能够递归地遍历Song
中的所有Sections
,每个Section
中的所有CompositeMusics
,并在每个CompositeMusic
中播放所有MusicTimes
。换句话说,迭代每种类型中的所有子类,除非它是MusicTime
,在这种情况下,请玩它
我天真地认为我可以在MusicComponent
基类上放置一个抽象的List<MusicComponent> getChildren()
,这样我就可以以同样的方式迭代任何后代。但是这是不允许的,因为它不接受List<Section>
例如
所以我的问题是,递归迭代同一基类派生的不同对象的正确方法是什么
编辑
根据要求,代码示例:
基类
public abstract class MusicComponent {
public MusicComponent() {
}
public abstract void play();
public abstract boolean addComponent(MusicComponent component);
public abstract List<MusicComponent> getChildren();
}
子类示例
public class Song extends MusicComponent {
String songName;
List<Section> sections;
public Song(String songName, List<Section> sections) {
this.songName = songName;
this.sections = sections;
}
这就是我想在Song
(以及Section
和CompositeMusic
上做的事情)
@Override
public List<MusicComponent> getChildren() {
return sections;
}
但是它抛出了一个编译错误,因为它不能隐式地从List<Section>
转换到List<MusicComponent>
,即使Section
是MusicComponent
的后代,这也是我希望能够做到的
# 1 楼答案
尝试使用
List<? extends MusicComponent>
作为返回类型# 2 楼答案
Java 1.5支持协变返回类型,因此基本上,如果基类方法被重写,getChildren()方法将能够返回MusicComponent子类的任何列表。您需要做的是在使用instanceof迭代检查之前,确保要迭代的列表变量的类型正确