Static Variables

This notebook will explain what static variables are, how they differ from instance variables, and provide examples, including a mini-project with broken code to fix.

1. Introduction to Static Variables

  • Static variables belong to the class rather than any particular instance. They are shared across all instances of the class.
  • Example:
public class BankAccount {
    // Static variable
    static double interestRate = 0.03;

    // Instance variable
    double balance;

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

    // Static method
    static void setInterestRate(double newRate) {
        interestRate = newRate;
    }
}

In this BankAccount class, interestRate is a static variable shared by all instances, and setInterestRate() is a static method that updates this variable.

2. Defining Static Variables

  • Static variables are defined using the static keyword and accessed using the class name.
  • Example:
public class Student {
    // Static variable
    static String schoolName = "XYZ School";

    // Instance variable
    String name;

    // Constructor
    public Student(String name) {
        this.name = name;
    }
}

// Accessing static variable
System.out.println(Student.schoolName);

Here, schoolName is a static variable shared by all Student instances.

3. Static Methods

  • Static methods can access static variables but cannot access instance variables directly.
  • Example:
public class BankAccount {
    static double interestRate = 0.03;

    static void updateInterestRate(double newRate) {
        interestRate = newRate;
    }
}

// Using static method
BankAccount.updateInterestRate(0.04);

The updateInterestRate method updates the static variable interestRate.

4. Mini Project: Fix the Code

  • Below is a class with broken code. The goal is to fix the class so it correctly implements and accesses static variables and methods.
  • Broken code:
public class Vehicle {
    static int count = 0; 

    // Constructor
    public Vehicle() {
        count++;
    }

    // method
    public static void displayCount() {
        System.out.println("Total Vehicles: " + count);
    }

    public static void main(String[] args) {
        Vehicle v1 = new Vehicle(); 
        Vehicle.displayCount(); 

        Vehicle v2 = new Vehicle(); 
        Vehicle.displayCount(); 

        Vehicle v3 = new Vehicle(); 
        Vehicle.displayCount(); 
    }
}


  • Task: Debug the Vehicle class to ensure count is properly incremented and displayed. Consider how displayCount() should be modified if count is a static variable.