CSC108 Lecture #6 - Static Review


Uses of static

  1. Classes can have static members. The static members belong to the class, not to a particular instance of the class, so that if one instance changes the static member, all other members would see these changes to this member. A static method is used to access or modify a static variable

  2. The other use of static that we have seen is something like Math.sin(...). The Math class groups together a number of static methods. No objects of the Math class are created. We call these methods using the name of the class, a dot, and the name of the method. There is no need to create an instance of the class because all of the information that is needed for these methods to operate is passed in through the parameter.

WashMash.java

class WashMach {
	// Static members go with the class (shared among
	// all instances of the WashMach class).
	private static double totalSales; // total sales
	private static int numMachines; // total machines
	private String name;  // which machine is it?
	private String contents; // what's in the machine

	public WashMach (String machName) {
		name = machName;
		numMachines++;
	}

	public void add (String item) {
		contents = item;
	}

	// Sample static method - modifies static member.
	public static void recordSale (double amount) {
		totalSales += amount;
	}

	public void printInfo () {
		System.out.print   ("Machine " + name);
		System.out.println (" contains "  + contents);
		System.out.println ("Totals: machines=" +
				numMachines + ", sales=$" + totalSales);
		// Demonstrates a static method call.
		TestWash3.doNothing ("junk");
    	}
}

TestStudent2.java

class TestWash3 {
	public static void main (String[] args) {
		WashMach mach1 = new WashMach ("01");
		WashMach mach2 = new WashMach ("02");
		mach1.add ("sock");
		mach2.add ("towel");
		mach1.recordSale (10.25);
		WashMach.recordSale (5.50);
		WashMach.recordSale (5.25);
		mach1.printInfo();
		mach2.printInfo();
	}

	// Sample static method - just prints its paramter.
	public static void doNothing (String data) {
		System.out.println ("doNothing param:" + data);
	}
}	

Output for TestWash3.java

Machine 01 contains sock
Totals: machines=2, sales=$21.0
doNothing param:junk
Machine 02 contains towel
Totals: machines=2, sales=$21.0
doNothing param:junk

[ CSC108 Home | Outline | Announcements | Newsgroup | Assignments | Lectures | Marks | Links ]


U of T IMAGE

© Copyright 2000. All Rights Reserved.