next up previous
Next: Lifetime of instance variables Up: Unit 03 Previous: Instance variables

Scope of instance variables

Instance variables are always visible in all methods of the class. They always refer to the invocation object.

Example: In the statement return name; the instance variable name is an instance variable of the invocation object for the method.

The public instance variables are visible outside the class, and they can be accessed through a reference to the object to which they belong, by means of the field selection operator ``.''.

Example: If we had defined the class to represent persons as follows:

public class Person2 {

  //instance variables (data fields)
  private String name;
  public String residence;        //residence is declared public

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

then we could directly access the instance variable residence, as shown by the following client:

public class ClientClassPerson2 {
  public static void main(String[] args) {
    Person2 p1;
    p1 = new Person2();
    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);
            //OK! the field residence is public
  }
}

Note: Typically, the instance variables must be declared private, to hide from the clients the representation of the objects of the class. This leaves the freedom to change such a representation without the need to modify the clients.


next up previous
Next: Lifetime of instance variables Up: Unit 03 Previous: Instance variables