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; }
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; } }
System.out.println(BankAccount.getRate());
BankAccount.setRate(0.05);