【发布时间】:2022-12-05 00:48:49
【问题描述】:
可以说我有这个:
主要的:
public class Main {
public static void main(String[] args) {
Orchestra orchestra = new Orchestra();
Drum drum = new Drum();
Xylophone xylophone = new Xylophone();
//----------------------------------
drum.sendToOrchestra();
xylophone.sendToOrchestra();
}
}
鼓:
public class Drum{
public void play(String note){
System.out.println("Playing... drums (note " + note + ")");
}
public void sendToOrchestra(){
Orchestra orchestra = new Orchestra(this);
}
}
木琴:
public class Xylophone{
public void play(String note){
System.out.println("Playing... xylophone (note " + note + ")");
}
public void sendToOrchestra(){
Orchestra orchestra = new Orchestra(this);
}
}
乐队:
public class Orchestra {
static Object[] instrumentsArray = new Object[2];
public Orchestra(){
}
public Orchestra(Xylophone xylophone){
// this works: xylophone.play()
instrumentArray[0] = xylophone;
// but this does not: instrumentsArray[0].play()
}
public Orchestra(Drum drum){
// this works: drum.play()
instrumentArray[1] = drum;
// but this does not: instrumentsArray[1].play()
}
public void playInstruments(){
// here is where I will iterate through the instrumentsArray, and make all elements inside it: .play()
}
}
我的问题是,如何在实例方法插入数组后访问它们?因为我可以在它们进入数组之前访问它们。
【问题讨论】:
-
你的乐器类应该只有 play 方法。您的主类应该负责实例化 Orchestra 类、乐器类,并将乐器实例添加到 orchestra 类。