next up previous
Next: Example for the design Up: Unit 03 Previous: Example for the design

Example for the design of a class: realization of the methods

We concentrate now on the various methods and realize their bodies.

We start from the constructor:

public Car(String p, String m, String c) {
  plate = p;
  model = m;
  color = c;
  owner = null;
}

Note: If we omit the statement owner = null; the owner will anyway automatically be initialized to null, which is the default value for references to objects. It is anyway a good programming practice to explicitly initialize all instance variables, thus avoiding to make use of the automatic initializations.

We realize the other methods in a similar way.

public class Car {
  // representation of the objects
  private String plate;
  private String model;
  private String color;
  private Person owner;

  // constructor
  public Car(String p, String m, String c) {
    plate = p;
    model = m;
    color = c;
    owner = null;
  }
  // other public methods
  public String getPlate() {
    return plate;
  }
  public String getModel() {
    return model;
  }
  public String getColor() {
    return color;
  }
  public Person getOwner() {
    return owner;
  }
  public void setColor(String newColor) {
    color = newColor;
  }
  public void setOwner(Person newOwner) {
    owner = newOwner;
  }
}


next up previous
Next: Example for the design Up: Unit 03 Previous: Example for the design