/* This program and notes explain the usage of *static* variables and methods */ class account // bank account class { // The following are instance variables: public String name; // "final means" can only set once protected double balance; public account(String n, double b) { name=n; balance=b; } public void transaction(double amt) // withdraw/deposit (amt can be <0) { balance += amt; } // The following is a "class variable" because it's not associated // with any specific instance of account. These variables are // marked "static". protected static double interestRate = 0.01; // Static is not the same as "final". Static variables can change: public static void changeInterest(double i) { interestRate = i; } // Note that this method is also static, because it only refers to // static variables. ***A static method may only refer to static // variables and call other static methods*** // Can the following function be static? public void addInterest() { balance += balance * interestRate; } // NO because it is referring to something non-static. That is, // this function is not independent of any specific instance of the class. // How about the following? public void mergeWith(account B) // merge this account with B { balance += B.balance; B.balance = 0; } // Absolutely not. balance == this.balance. The reference to *this*, even // if hidden, indicates that it cannot be called a static method. *this* // refers to the *instance* of the class that the method was invoked on. // How about this version of merge: public static account mergeAccounts(account A, account B) { account C = new account(A.name+" and "+B.name, A.balance+B.balance); A.balance = 0; B.balance = 0; return C; } // This is a valid static method because there is no reference to any // non-static instance variable or method except to local variables // A and B. No reference to *this*, hidden or explicit. }//account class // Now look at how static methods are called. public class statics { public static int x; // global variable: refer to as statics.x public static void main(String[] av) { account a1 = new account("abc",1000); account a2 = new account("xyz",2000); a1.transaction(-200); // withdraw $200 account.changeInterest(0.005); // half % interest account a3 = account.mergeAccounts(a1,a2); a3.mergeWith(new account("qrst",4000)); x = 2; // this.x += 1 System.out.println("Why can't I refer to *this* in main?"); } }