gpt4 book ai didi

Java 多态性与 ArrayList

转载 作者:行者123 更新时间:2023-12-01 22:33:08 25 4
gpt4 key购买 nike

我在 eclipse 中编写代码,我有一个名为 platform 的类和像 redplatform、blueplatform 这样的子类。我想创建一个可以存储 blueplatform 和 redplatform 的数组列表,到目前为止我已经做到了。

ArrayList<Platform> p = new ArrayList<Platform>();
private void createPlatform() {
switch (platform) {
case 0:
p.add(new GreenPlatform(x, y));
case 1:
p.add(new RedPlatform(x, y));
case 2:
p.add(new BluePlatform(x, y));
case 3:
p.add(new MagentaPlatform(x, y));
case 4:
p.add(new GrayPlatform(x, y));
}
repaint();
@Override
public void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
for (int i = 0; i < p.size(); i++) {
p.get(i).paint(g);
}
}

在每个类中,它都有一个 Paint 方法,可以将颜色设置为不同的颜色并进行绘制但现在它们都是灰色的。这令人沮丧。

最佳答案

switch (platform) {
case 0:
p.add(new GreenPlatform(x, y));
break;
case 1:
p.add(new RedPlatform(x, y));
break;
case 2:
p.add(new BluePlatform(x, y));
break;
case 3:
p.add(new MagentaPlatform(x, y));
break;
case 4:
p.add(new GrayPlatform(x, y));
}

关于Java 多态性与 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319139/

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