我要说的是:
Main:
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()
}
}我的问题是,在实例方法插入数组之后,如何访问它们?因为我可以在它们进入数组之前访问它们。
发布于 2022-12-04 16:46:51
我认为您混淆了类的关注点,并在类之间造成了太多的耦合。
主,应该是创建所有的对象。它将创建管弦乐队、鼓和木琴。然后,鼓和木琴实例将直接添加到管弦乐团实例的主要方法。
鼓和木琴根本不应该知道管弦乐队的课程。
然后,Main将访问playInstruments()方法的管弦乐团。
旁注
我建议鼓和木琴都实现一个名为that的接口,该接口有一个名为play(String note)的方法。所以管弦乐团不需要与特定的鼓声和木琴相连,它只需要有乐器,你以后就可以添加各种乐器,而无需编辑你的基础管弦乐队的类。
示例
可能的新管弦乐团班:
import java.util.ArrayList;
import java.util.List;
public class Orchestra {
private List<Instrument> instruments;
public Orchestra() {
this.instruments = new ArrayList<>();
}
public Orchestra(List<Instrument> instruments) {
this.instruments = instruments;
}
public void add(Instrument instrument) {
this.instruments.add(instrument);
}
public void play() {
this.instruments.forEach(i -> i.play("b flat"));
}
}仪器接口:
public interface Instrument {
void play(String note);
}鼓:
public class Drum implements Instrument {
@Override
public void play(String note) {
System.out.println("Drums: " + note);
}
}木琴:
public class Xylophone implements Instrument {
@Override
public void play(String note) {
System.out.println("Xylophone: " + note);
}
}最后,Main:
public class Main {
public static void main(String[] args) {
Orchestra orchestra = new Orchestra();
orchestra.add(new Drum());
orchestra.add(new Xylophone());
orchestra.play();
}
}https://stackoverflow.com/questions/74678669
复制相似问题