Instance Variables & ScopeHomepage  « Learn Java5 « Instance Variables & Scope

Java comes with three kinds of scope and we name variables according to the scope they reside in as detailed in the table below. In this lesson we focus on instance variable scope.

Variable Scope Lifetime
staticStatic variables apply to the class as a whole and are declared within the class but outside a method.Exists for as long as the class it belongs to is loaded in the JVM.
See the Static Members lesson for more information.
instanceInstance variables apply to an instance of the class and are declared within the class but outside a method.Exists for as long as the instance of the class it belongs to.
localLocal variables apply to the method they appear in.Exists until the method it is declared in finishes executing.
See the Method Scope lesson for more information.

Declaring Instance Variablesgo to top of page Top

In Java we declare variables anywhere within a block of code and instance variables are defined within a class but outside any methods. Instance variables can be declared anywhere within class scope, but by convention they are declared before any methods of the class and we will adhere to this. Lets return to our simple Cat class:

instance scope diagram

What is not apparent from the diagram is the difference between instance and local variables. Local variables always need to be initialized before use, instance variables are assigned a default value unless explicitly assigned one.

Instance variables are assigned a default value according to their type:

  • object - null
  • boolean - false
  • char - /u0000
  • integer types (byte, short, int and long) - 0
  • floating-point types (float, double) - 0.0

To prove this lets create an instance of our Cat class and display its instance variables:


/*
  Test Class3 for Cat
*/ 
public class TestCat3 {

    public static void main (String[] args) {
        Cat moggy = new Cat();    // Create a Cat instance
        System.out.println("Our " + moggy.colour + " cat called " + moggy.name + " is " + moggy.age);
    }
}

Save, compile and run the file in directory   c:\_ObjectsAndClasses in the usual way.

run instance variable default

The above screenshot shows the output of running our TestCat3 class. We created a Cat instance and displayed the values of its instance variables. The String objects default to null and the int primitive defaults to 0.

Looking At Object Statego to top of page Top

As mentioned earlier in this section each time we create a new instance of the class, that instance gets its own set of instance variables. The variables are completely unique to each instance and the values held within each instance are known as object state. Objects live on The Heap and as instance variables represents an Object State and so they also reside on The Heap within the appropriate instance of their object type. Lets take a closer look at what this actually means with our simple Cat class. Using the following slide show just press the button to step through each slide.

heap 6 heap 7 heap 8 heap 9

In this slide we create 3 Cat objects and these are placed on the Heap and can be accessed through their reference variables. At the moment all these objects are in their default state.

In this slide we assign values to the instance variables of the Cat object with a reference variable of moggy.

In this slide we assign values to the instance variables of the Cat object with a reference variable of tigger.

In this slide we assign values to the instance variables of the Cat object with a reference variable of tabby.

Press the button below to cycle through our Object State explanation.


Lets look at some code to illustrate the above scenario:


/*
  Test Class4 for Cat
*/ 
public class TestCat4 {

    public static void main (String[] args) {
        Cat moggy = new Cat();
        Cat tigger = new Cat();
        Cat tabby = new Cat();
        moggy.name = "Henry";    
        moggy.colour = "black";    
        moggy.age = 4;    
        tigger.name = "Kitty";    
        tigger.colour = "grey";    
        tigger.age = 15;    
        tabby.name = "Felix";    
        tabby.colour = "white";    
        tabby.age = 8;    
        System.out.println("Our " + moggy.colour + " cat called " + moggy.name + " is " + moggy.age);
        System.out.println("Our " + tigger.colour + " cat called " + tigger.name + " is " + tigger.age);
        System.out.println("Our " + tabby.colour + " cat called " + tabby.name + " is " + tabby.age);
    }
}

Save, compile and run the file in directory   c:\_ObjectsAndClasses in the usual way.

object state

The assignments of the reference variables happen as in the slide show and we print out the instance variables for each instance.

Final Instance Variablesgo to top of page Top

We can also make the value of an instance variable constant so it can't be changed after being given a value. You must always assign a value to an instance variable marked as final before using it or you get a compiler error:


/*
  Using a final instance variable before assignment
*/ 
public class A {
    final int i;

    A() {
        System.out.println(i);
    }   
}

run final instance variable

The above screenshot shows the result of trying to compile class A.

An instance variable that is marked as final can never change once it has been assigned a value. So once assigned a value, trying to change an instance variable marked as final will cause a compiler error:


/*
  Trying to reassign a final instance variable
*/ 
public class A {
    final int i = 1;

    A() {  // Constructor
        i = 2;
    }   
}

run final instance variable

The above screenshot shows the result of trying to compile class A. We will talk about about constructors later in this section.

You can also use the final keyword to create final local variables, within parameter lists, when creating java constants and for preventing inheritance/overriding.

Instance Variable Scopego to top of page Top

In our discussion on The Heap in the last lesson we mentioned that as long as we have a reference to an object then it exists on The Heap. Objects are eligible for removal from The Heap by the garbage collector when their scope ends and there are no live references to them, or they become unreachable, or the reference to the object is set to null. So what does this mean for our instance variables? Well as the instance variables are unique to an instance of their class it means when no reference variables point to that instance it and any instance variables attached to it go out of scope. So the lifetime of instance variables, aka their scope, are implicitly tied to the object they belong to, when the object dies so does its state.

Instance Variables & Scope Quizgo to top of page Top

Try the quiz below to test your knowledge of this lesson

Question 1 : What are variables created within a class and outside any method known as?
- Variables created within a class and outside any methods are known as instance variables.
Question 2 : Instance variables live on the stack?
- Instance variables live on the heap.
Question 3 : Instance variables are unique to their class
- Instance variables are unique to an instance of the class not the class itself.
Question 4 : What is the lifetime of an instance variable?
- An instance variable exists as long as the instance of the class it belongs to.
Question 5 : What do instance variables describe?
- Instance variables describe an objects state.
Question 6 : Instance variables are declared within a method?
- Instance variables are declared within a class and outside any methods
Status Bar Please select an answer

What's Next?

As we saw from our last practical, populating our instance variables can be pretty verbose and there is an easier way as we find out in the next lesson on constructors.

<<  Methods                    Constructors  >>

go to home page Java5 Tutor Homepage go to top of page Top