Skip to main content
IBM 
ShopSupportDownloads
IBM HomeProductsConsultingIndustriesNewsAbout IBM
Java Language EssentialsDownload tutorial zip fileEmail this tutorial to a friend
Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
Course Notes
  


Access methods page 12 of 37


In order for the value of an instance variable to vary over time, we must supply a method to change its value; such a method is typically referred to as an access method. By convention, a method that's provided simply to affect a change to an instance variable's value begins with the word "set":


  void setBark(String barkSound) {
    this.barkSound = barkSound;
  }

This method is interesting because it uses two different variables with the same name, barkSound. First, the barkSound defined as an parameter is the new barking sound. Any unqualified reference to barkSound within this method refers to this data passed as an argument. We also have, however, a barkSound instance variable for each dog that is instantiated. With Java(TM), we can use the special "instance handle" this to refer to the current instance of Dog. Hence,


    this.barkSound = barkSound;

replaces the current value of the instance variable (this.barkSound with the new value passed as an argument (barkSound) to setBark().

To put the this variable in perspective, suppose we create an instance of Dog referred to as fido. Then, if we execute setBark() with respect to fido, namely,


    fido.setBark("Ruff.");

the this instance in setBark()is fido and, in particular, this.barkSound is the barkSound instance variable for the fido object.

In the following version of DogChorus, we create an object, fido, change its barking characteristic from the default "Woof." to "Ruff.", and then invoke the barking behavior:


public class DogChorus {
  public static void main(String[] args) {
    Dog fido = new Dog();
    fido.setBark("Ruff.");
    fido.bark();
    System.exit(0);
  }
}

With this modification, the characteristics of an object such as fido are reflected by both the current values of instance/state variables and the available behaviors defined by the methods in Dog.

Exercise

copyright 1996-2000 Magelang Institute dba jGuru


Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
PrivacyLegalContact