我的目标是通过创建testInstrument.java文件打印出所有乐器正在演奏。由于某种原因,我收到了System.out.println(all[i].play());的错误
testInstrument.java
package my_instruments;
public class testInstrument {
public static void main(String[] args) {
// TODO Auto-generated method stub
Guitar g = new Guitar();
Flute f = new Flute();
Piano p = new Piano();
Instrument[] all = new Instrument[3];
all[0] = g;
all[1] = f;
all[2] = p;
for (int i=0; i<3; i++) {
System.out.println(all[i].play());
}
}
}Instrument.java
package my_instruments;
public class Instrument {
public Instrument() {
}
public void play() {
System.out.println("Playing instrument");
}
}Piano.java
package my_instruments;
public class Piano extends Instrument{
public Piano() {
super();
}
public void play() {
System.out.println("Playing piano");
}
}发布于 2018-02-20 01:29:52
试试这个:
for (int i=0; i<3; i++) {
all[i].play();
}play方法已经在执行打印,并且不会返回任何要打印的内容。
发布于 2018-02-20 01:32:56
您的play方法()正在执行打印操作,尝试从System.out.println();循环中删除打印语句
for (int i=0; i<3; i++) {
all[i].play();
}或
for (Instrument i : all) {
i.play();
}https://stackoverflow.com/questions/48871128
复制相似问题