next up previous
Next: Controlling the access to Up: Unit 03 Previous: Example of a class

Use of a defined class

A class defined by the programmer is used exactly in the same way as a predefined class (e.g., String).

public class ClientClassPerson {
  public static void main(String[] args) {
    Person p1;
    p1 = new Person();
    p1.setResidence("Roma");
    System.out.println(p1.getResidence());
  }
}

The class ClientClassPerson is a client of the class Person, since it makes use of such a class. The client defines the method main (the method of the program that is called first) in which:

  1. we define a variable, local to main, of type Person (or, more precisely, of type reference to an object that is an instance of Person);
  2. we create a new object of the class Person, and we assign to p1 a reference to it;
  3. we call the method setResidence of the class Person on the object denoted by p1, and pass to the method the actual parameter "Roma"; note the use of the selection operator ``.'' to select the (public) fields of the class (in this case, the method setResidence);
  4. finally, we call the method getResidence on p1 to print the residence of the object denoted by p1.

Note: The class ClientClassPerson must be saved in a file called ClientClassPerson.java. The file must be placed in the same directory as the file containing the class Person, in order to avoid problems during the compilation or the execution of the class ClientClassPerson. We could overcome this limitation by making use of so called packages, but we will not deal with packages in this course.


next up previous
Next: Controlling the access to Up: Unit 03 Previous: Example of a class