Class declarations and object modeling: Correct Solution


Translate the specification below into an idiomatic Java class definition.

(In this context, "idiomatic" means following the common style and conventions of the language.)

  1. One kind of thing that exists in our model is an Iarba.

  2. Each Iarba has its own ontse, which is a graphics object. The value of ontse is specified when a Iarba is created. Anyone can ask an Iarba for the value of its ontse. The value of ontse for a specific Iarba can never change.

  3. All Iarbas share a single pel, which is a graphics object. No other classes can directly ask for the value of pel. The value of pel starts out as a rectangle with a width of 38 and a height of 28 when the program starts. Every time a new Iarba is created, it moves pel to the right by 3 pixels (using the moveBy method).

  4. Each Iarba has a cuHaene, which is a graphics object. A cuHaene is part of the internal state of an Iarba: no other classes can see the value of cuHaene or directly change it. When an Iarba is first created, the value of its cuHaene starts out as an ellipse with a width of 19 and a height of 44.

  5. Each Iarba has a pid, which is an int. The value of pid is not part of an Iarba’s internal state; instead, it is computed on demand. The computed value of pid is the x position of cuHaene.

  6. An Iarba can worify. This behavior moves cuHaene to the right by 2 pixels (using the moveBy method). Anyone can ask an Iarba to worify.

Solution

public class Iarba {
    public static GraphicsObject pel;
    private GraphicsObject ontse;
    public GraphicsObject cuHaene = new Ellipse(0, 0, 19, 44);
    private int pid;

    public Iarba(GraphicsObject ontse) {
        this.ontse = ontse;
        pel.moveBy(3, 0);
    }

    public GraphicsObject getOntse() {
        return ontse;
    }

    public void setOntse(GraphicsObject ontse) {
        this.ontse = ontse;
    }

    public static void onStart() {
        pel = new Rectangle(0, 0, 38, 28);
    }

    public int getPid() {
        return cuHaene.getX();
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    private void setWorify() {
        cuHaene.moveBy(2, 0);
    }
}

Things to check in your solution:

Acceptable variations in the solution:


Related puzzles: