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

Example for the design of a class: public interface

We are now ready to choose the interface of the class Car, through which the clients can use its objects. In particular, for each functionality we have to define a public method realizing it and determine its header.

The requested functionalities are:

Creation of an object of the class with the properties plate, model, and color, suitably initialized, and no owner.

We know that, to construct an object of a class, we have to use a constructor. Hence, this functionality requires the definition of a constructor; specifically, this constructor must initialize the instance variables that represent plate, model, and color using suitable parameters (note that the first two properties cannot change value anymore). The instance variable owner, instead, must be initialized to the non-significant value null. The header of the constructor is:

public Car(String p, String m, String c)

Return of the value of each of the properties plate, model, color, and owner.

For each of the four properties, we define a public method that return the value (to be precise, the reference to the object that represents the value). The headers of these methods are:

public String getPlate()
public String getModel()
public String getColor()
public Person getOwner()

Modification of the value of the properties color and owner.

To modify the color and the owner we introduce two methods whose header is:

public void setColor(String newColor)
public void setOwner(Person newOwner)

At this point we can write the skeleton of the class Car:

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) {
    ...
  }
  // other pubblic methods
  public String getPlate() {
    ...
  }
  public String getModel() {
    ...
  }
  public String getColor() {
    ...
  }
  public Person getOwner() {
    ...
  }
  public void setColor(String newColor) {
    ...
  }
  public void setOwner(Person newOwner) {
    ...
  }
}

Note: Since we have introduced a constructor, we cannot use anymore the standard constructor. On the other hand, we are not interested in defining a constructor without arguments, since we need to fix the plate and the model of an object Car once and for all the moment it is created.


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