next up previous
Next: Variable Summary Up: Varieties of Variables Previous: Method Parameters

Static or Class Variables

A static or class variable is a variable that is associated with the class, rather than objects of the class. Its scope is determined in the same manner as instance variables: private means that only methods of the same class can access it while public allows wider access (we'll define what we mean by 'wider access' at a later date. Let's stick to private variables for now.)

The lifetime of a static variable begins when the class definition is loaded -- that is, when the program starts to run, for example. Therefore, we can access a static variable even if we haven't instantiated any object yet.

In addition, we can instantiate as many objects as we like, but we'll only ever have one version of the class variable. In contrast, every time we create a new Student object, for example, we get a new version of the variables name, age, and so on. Presumably we'll set these variables to the appropriate values for each individual student. So instance variables describe some property of each individual instantiation of a class, while class variables are used to describe something about the class as a whole. For example, we might want to keep track of the number of students who have registered so far. Clearly this attribute refers to the class Student as a whole, not to each individual student. Our class definition would then look like:


public class Student {
  
  
    public void PayFees(double someamount) {
        feesOwing = feesOwing - someamount;
    }

    private static int numStudents = 0;

    private String name;
    private int age;
    private String courses;
    private double feesOwing = 5000.00;
    private boolean scholarship;
}

Here we've added an integer variable called numStudents to the class definition. Being static, no matter how many students we instantiate, there is only one copy of numStudents. But how would we actually change the value of numStudents?


next up previous
Next: Variable Summary Up: Varieties of Variables Previous: Method Parameters
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09