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

Example for the design of a class: a client

Let us realize a client, CarServices, of the class Car. The class CarServices contains two static methods:

We write the class CarServices, in a file called CarServices.java, as follows:

public class CarServices {
  public static void spray(Car car, String color) {
    car.setColor(color);
  }
  public static Car registerAlfa147(String pla, String col) {
    return new Car(pla, "Alfa147", col);
  }
}

Finally, we realize a class Main, containing a method main, that uses the class Car and the class CarServices. This class will be written in a separate file Main.java:

public class Main {

  // auxiliary method
  private static void printCarData(Car a) {
    System.out.println("Car: " + a.getPlate() + ", "
                               + a.getModel()+ ", "
                               + a.getColor());
  }

  // auxiliary method
  private static void printOwnerData(Car a) {
    System.out.println("Owner: " + a.getOwner().getName() + ", "
                                 + a.getOwner().getResidence());
  }

  public static void main(String[] args) {
    Car a = new Car("313","Fiat 500","Red and Blu");
    printCarData(a);
    Person p = new Person("Paperino", "Paperopoli");
    a.setOwner(p);
    printOwnerData(a);
    CarServices.spray(a, "Maranello Red");
    printCarData(a);
    Car b = CarServices.registerAlfa147("131", "Alfa Red");
    printCarData(b);
    Person c = new Person("Clarabella", "Topolinia");
    b.setOwner(c);
    printOwnerData(b);
  }
}


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