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
  


Instance variables page 11 of 37


So far, we're defining instances of objects in terms of their behaviors, which in many cases is legitimate, but, in general, user-defined data types incorporate state variables as well. That is, for each instance of Dog, it's important to support variability with respect to characteristics such as hair color, weight, and so on. State variables that distinguish one instance of Dog from another are called instance variables.

Now suppose we add an instance variable to reflect a particular dog's barking sound; a String instance can represent each dog's bark:


class Dog {
  String barkSound = new String("Woof.");

  void bark() {
    System.out.println(barkSound);
  }

  void bark(String barkSound) {
    System.out.println(barkSound);
  }
}

The definition of Dog now includes the instance variable barkSound. Each time a new instance of Dog is created, that instance will include a reference variable for an instance of String representing that particular dog's bark. This instance variable is initialized to the default value of "Woof.". Consider the line of code


  String barkSound = new String("Woof.");

This statement allocates an instance of String, initializes it with the value "Woof." (provided in the parentheses following the String class name), and stores this data under the reference variable barkSound. Note that the reference variable barkSound is part of each instance of Dog, but that it references an instance of String that's allocated on the heap, as is the instance of Dog:

Now that the default barking behavior is represented by an instance variable, we can remove the "Woof." data from the original bark() method, replacing it with a reference to the current value of barkSound:


  void bark() {
    System.out.println(barkSound);
  }

That is, we've transferred unconditional state data from a method definition into an instance variable that can vary from one dog to the next, and perhaps more importantly, for a particular dog, its value can change dynamically.


copyright 1996-2000 Magelang Institute dba jGuru


Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
PrivacyLegalContact