gpt4 book ai didi

java - 使用Java多态性

转载 作者:行者123 更新时间:2023-12-01 19:57:51 25 4
gpt4 key购买 nike

我的目标是通过创建 testInstrument.java 文件打印出所有乐器正在演奏。由于某种原因,我收到 System.out.println(all[i].play());

的错误

测试仪器.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());
}


}

}

仪器.java

package my_instruments;

public class Instrument {

public Instrument() {

}

public void play() {
System.out.println("Playing instrument");
}
}

钢琴.java

package my_instruments;

public class Piano extends Instrument{
public Piano() {
super();
}

public void play() {
System.out.println("Playing piano");
}
}

最佳答案

试试这个:

for (int i=0; i<3; i++) {
all[i].play();
}

play 方法已经在进行打印,并且没有返回任何要打印的内容。

关于java - 使用Java多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com