2D model simulating water breaking a floodbank For a homework assignment we have to write a class that simulates water breaking a floodbank (very simplistic 2D simulation).

My implementation works fine but I found that there were many downcasts (in my opinion, a flaw in Greenfoot's API, which should be using generic functions rather than functions that take classes as arguments, but I'm not sure if this is possible in Java since this is the first time I'm writing Java code).

Sandstone and Sand both derive from Actor, which is from Greenfoot.

import greenfoot.*;

public class Water extends Actor {
    public Water() {
        getImage().scale(64, 64);
    }

    public void act() {
        if (((DoorbraakWorld)getWorld()).stopped) return;

        if (Math.random() &lt; 0.9) return;

        int dx = 0, dy = 0;
        switch ((int)(3.0 * Math.random())) {
            case 0: dx = 0; dy = 1; break;
            case 1: dx = 1; dy = 0; break;
            case 2: dx = -1; dy = 0; break;
        }

        // The next line looks so incredibly ugly…
        Sandstone sandstone = (Sandstone)getOneObjectAtOffset(dx, dy, Sandstone.class);
        if (sandstone != null) {
            getWorld().removeObject(sandstone);
            getWorld().addObject(new Water(), getX() + dx, getY() + dy);
        }

        Sand sand = (Sand)getOneObjectAtOffset(0, 1, Sand.class);
        if (sand != null) {
            ((DoorbraakWorld)getWorld()).stopped = true;
            return;
        }
    }
}


Could I reduce the number of downcasts or is it normal for Java code to contain many downcasts? What else could I improve?
Downcasting can usually be avoided by using common methods in abstract types.

    if (((DoorbraakWorld)getWorld()).stopped) return;


Is this the same as getWorld().stopped()?

    // The next line looks so incredibly ugly…
    Sandstone sandstone = (Sandstone)getOneObjectAtOffset(dx, dy, Sandstone.class);
    if (sandstone != null) {
        getWorld().removeObject(sandstone);
        getWorld().addObject(new Water(), getX() + dx, getY() + dy);
    }


You can use the Actor type: Actor sandstone = getOneObjectAtOffset(dx, dy, Sandstone.class)

    Sand sand = (Sand)getOneObjectAtOffset(0, 1, Sand.class);


Here too: Actor sand = getOneObjectAtOffset(0, 1, Sand.class);

    ((DoorbraakWorld)getWorld()).stopped = true;


How about greenfoot.stop()?