DALLASCAO.COM

Site of Cao Shouguang, English to Chinese translator

Learn java: static variable


public class Car {

	/**
	 * Car.counter will output 2
	 */
	String make;
	String model;
	int numDoors;
	static int counter;
	// constructor, applying to all cars
	Car(String make, String model, int numDoors) {
		this.make = make;
		this.model = model;
		this.numDoors = numDoors;
		counter++;
	}
	//constructor set default numDoors to 4 
	Car(String make, String model) {
		this(make,model,4);
	}
	//method
	String drivenBy(String driver) {
		return driver;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		Car yourCar = new Car("Mazda", "RX-8", 3);
		Car myCar = new Car("Toyota", "Camry"); // numDoors is 4 when this parameter is omitted
		System.out.println("My car has " + myCar.numDoors + " doors");
		System.out.println("Your car has " + yourCar.numDoors + " doors");
		System.out.println("Your car is driven by " + yourCar.drivenBy("your wife"));
		System.out.println("how many cars? " + Car.counter);
	}

}

Notice the different between the two int variables, numDoors & counter.
counter is per class, meaning it will not be reset to 0 when a new object is created ( Car myCar = new Car …). And it should be accessed via classname.counter, ie. “Car.counter” not “myCar.counter”.

On the other hand, numDoors is per object. it will be reset to 0 when a new object is created and should be accessed via objectname.counter, ie. “yourCar.numDoors”

Leave a Comment