yuzhengwen
yuzhengwen

Reputation: 1

Java Polymorphism with ArrayLists

I write my code in eclipse, I have a class called platform and subclasses like redplatform, blueplatform.I want to create an arraylist which can store both blueplatform and redplatform,I have done this so far.

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

In each class, it has a paint method that sets color to something different and paints it but right now all of them are gray. This is frustrating.

Upvotes: 0

Views: 92

Answers (1)

tianz
tianz

Reputation: 2183

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

Upvotes: 3

Related Questions