next up previous
Next: Use of a defined Up: Unit 03 Previous: Definition of a class

Example of a class definition

We want to realize a Java class to represent persons. The properties of interest for a person object are the name, defined once and for all, and the residence, which may change.

Let us define a Java class Person to represent persons.

public class Person {
  //instance variables (data fields)
  private String name;
  private String residence;

  //methods (operation fields)
  public String getName() {
    return name;
  }
  public String getResidence() {
    return residence;
  }
  public void setResidence(String newResidence) {
    residence = newResidence;
  }
}

The definition of the class Person consists of the following elements:

The keywords public and private specify which fields are public and which are private (see later).

When a method, such as setResidence, modifies the object on which it is called we say that it has a side-effect (see, e.g., the methods of the class StringBuffer). In general, the decision whether a method of a class should have a side-effect or not is a design choice that has important consequences on the way in which the class must be used by its clients.

Note: The definition of a class has to be saved in a file with the same name as the class and extension .java. For example, the definition of the class Person must be saved in a file called Person.java.

Note: In the definition of a class, the order of the fields (instance variables and methods) is irrelevant.


next up previous
Next: Use of a defined Up: Unit 03 Previous: Definition of a class