【问题标题】:Java Polymorphism with ArrayListsArrayLists 的 Java 多态性
【发布时间】:2015-02-03 19:33:37
【问题描述】:

我在eclipse中编写代码,我有一个名为platform的类和redplatform,blueplatform等子类。我想创建一个可以存储blueplatform和redplatform的arraylist,到目前为止我已经做到了。

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);
    }
}

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

【问题讨论】:

    标签: java arraylist polymorphism subclass superclass


    【解决方案1】:
    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));
    }
    

    【讨论】:

    • 我明白了,我一直在犯这个错误!但这对程序有何影响? break 不就是跳出 for 循环吗?由于 int 平台只有一个 int,所以其中一个 case 会执行,而其他 case 不会,对吧?
    • @yuzhengwen switch 的工作原理是这样的:一旦匹配了一个 case 并且你没有破坏它,那么匹配 case 之后的每个语句都会被执行,即使它们处于不同的 case 下。例如,如果 case 2 匹配并且您不使用 break,则 case 2、case 3、case 4 下的所有内容都将被执行。在这里阅读更多:docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2011-02-16
    • 2013-12-05
    相关资源
    最近更新 更多