MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
  • Unit 3: Class Creation
    • Part 1: Basic Concepts
    • Part 2: Methods
      • Methods: How to Write Them
      • Methods: Passing and Returning References of an Object
      • Class Variables and Methods
      • Scope and Access
      • this Keyword
      • Unit 3 Part 2 Slides
  • Unit 4: Data Collections

Unit 3.7: Static Variables and Methods

The static keyword is used to create members (variables and methods) that belong to the class itself, rather than to individual objects.

Class (Static) Variables

Class variables (also called static variables) belong to the class.

Shared Class State
  • Static variables exist independent of any object. They are initialized when the class is first loaded and provide a single shared storage location for every instance of that class.
  • One Shared Copy: All objects of a class share a single copy of the static variable. If one object changes it, every other object sees that change immediately.
  • The static Keyword: They are designated with the static keyword before the variable type.

Think of it like a Shared Scoreboard in a game. There are many players (objects), but only one scoreboard (static variable) that everyone looks at and updates.

Task: Implementing shared state using a static variable.

public class Player
{
    // Shared by ALL Player objects
    public static int teamScore = 0; 
    
    // Unique to EACH Player object
    private int myScore = 0; 
}

Accessing Static Variables

Static variables that are public can be accessed from outside the class using the class name and the dot operator.

  • Best Practice: You should access them using the class name, not an object reference, because they are associated with the class.

Task: Accessing static variables using the class name.

public class School
{
    public static int totalStudents = 0;

    public School()
    {
        totalStudents++; // Update the shared count
    }
}

// In another class:
System.out.println(School.totalStudents); // Access using Class Name

Static Method Access

Class methods (static methods) are associated with the class, not with any specific object instance.

Static Scope Limitation
  • Static methods do not have access to this. They can only interact with instance data if that data is explicitly passed to them as an argument.

Because of this, they have several strict rules:

  1. No Direct Instance Access: They cannot access or change instance variables directly.
  2. No Direct Instance Method Calls: They cannot call instance methods directly.
  3. No this Reference: Static methods do not have a this reference because there is no "current object" context.

How to use instances in static methods: If a static method needs to interact with an instance, a reference to that instance must be passed as a parameter.

Task: Accessing instance data from within a static method.

public class Logger
{
    private String logName;

    // Static Method
    public static void printInfo(Logger obj)
    {
        // System.out.println(logName); // ERROR: Cannot see instance variable
        System.out.println(obj.logName); // OK: Accessing via parameter
    }
}

Static Context

While static methods cannot see instance data, they can access other static members.

  • Static methods can access or change other class variables.
  • Static methods can call other class methods within the same class.

Task: Calling static methods and accessing static variables from within a static context.

public class MathHelper
{
    public static int callCount = 0;

    public static int add(int a, int b)
    {
        updateCount(); // OK: Calling another static method
        return a + b;
    }

    private static void updateCount()
    {
        callCount++; // OK: Accessing static variable
    }
}

Final Variables (Constants)

You first encountered the final keyword in Unit 1.2 (Variables and Data Types) as a way to create local constants. In this unit, we combine static and final to create class constants.

Global Constants
  • static final variables provide a way to define values that are globally accessible, shared by all instances, and guaranteed never to change. By convention, these are named in ALL_UPPERCASE.

When a variable is declared with the final keyword, its value cannot be modified after it has been initialized.

Task: Defining and using a global class constant.

public class Config
{
    // A constant that is shared by everyone and never changes
    public static final double VERSION = 1.0;

    public static void main(String[] args)
    {
        System.out.println(Config.VERSION);
        // Config.VERSION = 2.0; // COMPILE ERROR: Cannot assign to final variable
    }
}

Final with Object References

It is a common misconception that declaring an object reference as final makes the object itself immutable.

  • Reference is Constant: The final keyword ensures that the reference variable will always point to the same object. You cannot reassign it to a new object.
  • Object State is Mutable: You can still modify the internal state of the object (by calling its methods or changing its public fields), provided the class allows it.

Task: Modifying the internal state of a final object reference.

public class Person {
    private String name;
    public Person(String n) { name = n; }
    public void setName(String n) { name = n; }
}

// In another class:
final Person p = new Person("Alice");

p.setName("Bob"); // ALLOWED: Modifying the object's internal state
// p = new Person("Eve"); // COMPILE ERROR: Cannot reassign a final reference
Privacy Policy | Terms & Conditions