Saturday, May 7, 2011

INSTANCE AND STATIC VARIABLES AND METHODS

One twist of complexity is that some state information and some behaviors belong to the class, while others
belong to the instances of a class. For instance, we would maintain the speed of each Automobile as part of
the state of each individual car (part of the state of each instance). On the other hand, we would maintain a
count of the total number of Automobiles as part of the state of the class Automobile. It seems natural
that speed should be associated with a particular car, but we need a central place to keep track of the total
number of Automobiles.
Perhaps we’re stretching the analogy a little bit, but
imagine a Ford on the road. It has a speed we can
measure, but after the Ford exits the factory, there is no easy way for the Ford to be kept apprised of the total
number of Automobiles that have been built. If we want to know how many Automobiles have been
built, we must go back to the factory and get the count. The factory is the class.

Variables like speed, which represent the state of an instance of a class, are called instance variables.
Variables like count, which are maintained by the class itself, are called static variables. The word static
means many things in computer science, and this use of the word static may be confusing. Other languages label
the same idea with a different name; for example, Visual Basic calls variables of this kind “shared” variables,
because they’re shared by all instances of a class. That term may be more helpful as you learn, so when you see
“static,” think to yourself “shared,” or “class.”
Similarly, methods can be instance methods or static methods. If two different instances of a class both
call the instance method accelerate(), it will be as if there were two different copies of that method, and
each instance had its own. (In reality, there will not be two copies of the code, but each instance will get its own
“stack” for local variables, which will keep the execution of the two calls separate, as if the code existed in two
places.) On the other hand, if two different instances of a class call the static method getAutomobileCount(),
the two instances will be using exactly the same code, because there is only one copy, and that is shared.
Variables and methods will always be instance variables and methods, unless you specifically label them
static. If you label a variable or method static, the variable or method will exist only at the level of the
class, and will be shared among the instances.
Below is our example Automobile class. Notice that there is no main method in the Automobile
class. This class cannot be executed directly. If we were to add a public main method, the class could be executed,
and whatever the main method were coded to accomplish would be done. However, this Automobile
class is intended to be a “factory” to create Automobile objects for use by other programs and classes,
rather than to be a program to be run by itself. You can think of the Automobile class as creating a new data
type—Automobile.
Notice also that in the class Automobile there is a method named Automobile; the name of the
method is the same as the name of the class. The method named Automobile is the constructor for the class.
Whenever another program needs an instance of an Automobile, the other program will use the new keyword
to request a new Automobile. We can tell from the Automobile constructor that the constructor
expects four parameters whenever a new Automobile is requested; these are the make, the model, the year,
and the horsepower. The first two parameters are String values, and the last two are ints.
When another program asks for an instance of an Automobile, the constructor will create an
Automobile object and return to the other program a reference to the new Automobile. A reference is an
address. The other program can then use the reference to the new Automobile object to manipulate it.
/**Class Automobile
* Illustrating instance and static varibles
* and methods
* @author Carl Reynolds
*/
class Automobile {
//static variable
private static int count; //count of automobiles
//instance variables
private String make;
private String model;
private int year;
private int hp;
private double speed;
//Constructor
Automobile( String mk, String mdl, int yr, int power ) {
make = mk; //assign constructor parameters
model = mdl; // to private instance variables
year = yr;
hp = power;
count++; //add to count of Automobiles created
}

//static method
static int getCount() {
return count;
}
//instance methods to set and get speed
public void accelerate( double newSpeed ) {
if( newSpeed > 70. ) speed = 70.;
else speed = newSpeed;
}
public double getSpeed() { return speed; };
//returns a text representation of an Automobile
public String toString() {
return year + " " + make + " " + model;
}
}
Here is a class which uses the Automobile class:
/**
* Class AutomobileFactory
* @author Carl Reynolds
*/
class AutomobileFactory {
public static void main( String[] args ) {
Automobile economy, family, sports;
economy = new Automobile(
"Kia", "Rio", 2006, 110 );
family = new Automobile(
"VW", "Passat", 2002, 170 );
sports = new Automobile(
"Ford", "Mustang", 2005, 300 );
System.out.println(
Automobile.getCount() + " Automobiles" );
System.out.println( economy );
System.out.println( family );
System.out.println( sports );
}
}
The class AutomobileFactory can be executed directly, because it has a main method coded in
the standard way. The main method declares three variables to be of type Automobile (notice you can
declare several variables of the same type on one line, as we did here), and then it creates three Automobile
objects by using the new keyword to invoke the constructor for the Automobile class three different
times.
The first println statement calls the static method getCount() by specifying the class name
Automobile, followed by a dot (period), followed by the method name getCount(). The getCount()
method will return the number 3, because each time the constructor of the Automobile class generates a new
Automobile, it increments its static count variable.

Finally, the three println statements at the end print a text representation of each Automobile. Such
use of an object’s name, such as economy, inside println causes the JVM to use the toString() method
of the class. When that happens here, the result on the screen is this:
3 Automobiles
2006 Kia Rio
2002 VW Passat
2005 Ford Mustang

No comments:

Post a Comment