CSC108 Lecture #6 - Static Review 2


static example

Here is another static example. We create two bank account objects (acct1 and acct2). These objects share the static 'bankTotal' variable. If acct1's deposit method deposits into the 'bankTotal' variable, then the change to this variable is also seen by acct2.

Notice that a "\n" is used to give a new line.

In summary, you should use static methods if your method does not use any instance variables.


BankAccount.java

class BankAccount {
	private static double bankTotal;
	private double balance;

	public void deposit (double amount) {
		balance += amount;
		bankTotal += amount;
	}

	public String toString () {
		return "Balance=" + balance + "\n" + "Bank Total=" + bankTotal;
	}
}

Bank.java

class Bank {
	public static void main (String[] args) {
		BankAccount acct1 = new BankAccount ();
		BankAccount acct2 = new BankAccount ();

		// Deposit $15 into account 1 and print balances
		acct1.deposit (15);
		System.out.println ("Account 1: " + acct1.toString());
		System.out.println ("Account 2: " + acct2.toString());
		System.out.println ();

		// Deposit $20 into account 2 and print balances
		acct2.deposit (20);
		System.out.println ("Account 1: " + acct1.toString());
		System.out.println ("Account 2: " + acct2.toString());
	}
}	

Output for Bank.java

Account 1: Balance=15.0
Bank Total=15.0
Account 2: Balance=0.0
Bank Total=15.0

Account 1: Balance=15.0
Bank Total=35.0
Account 2: Balance=20.0
Bank Total=35.0

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


U of T IMAGE

© Copyright 2000. All Rights Reserved.