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.
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; } }
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 $15 into account 2 and print balances acct2.deposit (20); System.out.println ("Account 1: " + acct1.toString()); System.out.println ("Account 2: " + acct2.toString()); } }
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
[ CSC108 Home | Outline | Announcements | Newsgroup | Assignments | Lectures | Marks | Links ]
© Copyright 2000. All Rights Reserved.