CSC108 Lecture #3 Example


WashMach.java

/**
 * WashMach models the behaviour of a washing
 * machine by printing strings to represent
 * actions, clothes being washed, etc.
 */
class WashMach {

	private String name;  // which machine is it?
	private String contents; // what's in the machine

	public void open () {
		System.out.println ("The lid is open.");
	}

	public void close () {
		System.out.println ("The lid is closed.");
	}

	public void start () {
		System.out.println ("Start washing ...");
		System.out.println ("Contents are clean.");
	}

	public void printIdentity () {
		System.out.println("Identity: machine "+name);
	}

	public void setIdentity (String id) {
		name = id;
	}

	public String getIdentity () {
		return name;
	}

	public void add (String item) {
		System.out.println ("Added " + item);
		contents = item;
	}

	public void printContents () {
		System.out.println ("Inside you will find " + contents);
	}

	public String getContents () {
		return contents;
	}
}

TestWash.java

// This version shows how to use all of the methods
// that have been created so far.

public class TestWash {

    public static void main (String[] args) {	

	WashMach myWashMach;
	myWashMach = new WashMach();

	// Give a value to the instance variable
	myWashMach.setIdentity ("Mr. Clean");
		
	System.out.println ("Your washing machine will now speak to you.");

	// There are two ways to print the identity
	myWashMach.printIdentity();
	System.out.println ("Identity: machine " +
				myWashMach.getIdentity());

	// Now let's add a sock
	myWashMach.open();
	myWashMach.add ("sock");
	myWashMach.close();
	myWashMach.start();

	// There are two ways to print the contents
	myWashMach.printContents();
	System.out.println ("Machine contains: " +
				myWashMach.getContents());
    }
}

Output

Your washing machine will now speak to you.
Identity: machine Mr. Clean
Identity: machine Mr. Clean
The lid is open.
Added sock
The lid is closed.
Start washing ...
Contents are clean.
Inside you will find sock
Machine contains: sock

[ Home | Outline | Announcements | Newsgroup | Assignments | Exams | Lectures | Links ]


U of T IMAGE

© Copyright 2000. All Rights Reserved.