static Variables and Methods

static Variables and static Methods

Static variables should be used to track data that are shared in common by all of the instances of a class. These variables are also called class variables. Class variables are distinguished from instance variables. Instance variables track the data that belong to each individual object of a class. put another way, there is a single area of storage reserved for class variables, whereas each object or instance of a class is allocated a separate storage area for its instance variables.

For example, a BankAccount class might declare an instance variable balance, because each account has its own distinct balance. If all of the accounts have the same interest rate, this value can be stored in a class variable. The next code segment shows a class definition in which these two data items are declared and initialized. The code also includes methods to make a deposit and compute interest for an account.


public class BankAccount{

    // Instance variable   
    private double balance;

    // Constructor
    public BankAccount(double b){
       balance = b;
    }

    // Deposits the amount
    public void deposit(double amount){
        balance += amount;
    }

    // Computes, deposits, and returns interest
    public double computeInterest(){
        double interest = balance * rate;
        deposit(interest);
        return interest;
    }
 
    // Class variable
    static private double rate = 0.2;
}

If we want to examine or change the interest rate, we’ll need methods, because the class variable rate is declared private. That’s a job for static methods. A static method can access or modify static variables, but cannot access or modify instance variables. static methods are also called class methods. The next code segment adds static accessor and mutator methods to the BankAccount class, so the client code can view or change the interest rate:

public class BankAccount{

    // Instance variables, constructor, and instance methods go here   
    
 
    // Class variable
    static private double rate = 0.2;

    // Class methods
    static public double getRate(){
        return rate;
    }

    static public void setRate(double r){
        rate = r;
    }
}

The client then can call the static methods, even before any instances are created, as follows:

System.out.println(BankAccount.getRate());
BankAccount.setRate(0.05);

© Ken Lambert. All rights reserved.