next up previous
Next: Rules for accessing the Up: Unit 03 Previous: Use of a defined

Controlling the access to the fields of a class

The access modifiers public and private have the following meaning:

Example:

public class ClientClassPerson2 {
  public static void main(String[] args) {
    Person p1;
    p1 = new Person();
    p1.setResidence("Roma");
                 //OK! the field setResidence is public
    System.out.println(p1.getResidence());
                 //OK! the field getResidence is public
    System.out.println(p1.residence);
                 //ERROR! the field residence is private
  }
}

This example shows a client that tries to access the public and private fields of the class Person. While the access to the public fields, setResidence and getResidence, is allowed, the access to the private field, residence, causes an error at compile time.


next up previous
Next: Rules for accessing the Up: Unit 03 Previous: Use of a defined