Reference Guide

Concept Key idea Java example Important note
Instance variable Belongs to an individual object private String name; Every object gets its own copy
Class variable Belongs to the class and is shared by all objects private static int numberOfStudents; Declared with static
static Makes a variable/method belong to the class rather than an instance public static int count; Access class members through the class when appropriate
Public class variable A class variable accessible outside its class public static int players; Access with Game.players
Class method A method belonging to the class public static int doubleValue(int x) Can be called without creating an object
Static method access Static methods can access static/class members count++ They cannot directly access instance variables
Dot operator Used to access public class members MathHelper.doubleValue(5) Typically ClassName.member
final variable A variable whose value cannot be reassigned after initialization public static final int DAYS_IN_WEEK = 7; Often used for constants
Shared state All instances see the same class-variable value Student.numberOfStudents Changing it affects what all objects see
Constructor + static variable A constructor can update shared class state numberOfStudents++; Useful for tracking how many objects have been created

Collegeboard Requirements

  • 3.7.A Develop code to define behaviors of a class through class methods.
    • 3.7.A.1 Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
    • 3.7.A.2 Class methods can access or change the values of class variables and can call other class methods
  • 3.7.B Develop c

Lesson Objectives/Plan

  • Define class variables and class methods using static
  • Explain how class variables are shared by all objects of a class, and what class methods can/cannot access
  • Use a class name and dot operator to access public class variables/methods
  • Explain what the final keyword does

Code Examples

Instance vs. Class Variables

Recall that an instance variable belongs to an individual object, so let’s say we have:

Code Runner Challenge

Modify the code so that creating each `Student` automatically increments the shared `numberOfStudents` counter.

View IPYNB Source
public class Student {
    private String name;
    private int grade;
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

and we define 3 students

Code Runner Challenge

Fix the code so that `printName()` can still be a `static` method. You might have to change what the method accepts.

View IPYNB Source
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Each student gets their own name and grade.

Class variables are different in that they belong to the class itself:

public class Student {
    private String name;
    private int grade;

    public static int numberOfStudents = 0;
}

Now, each student s1, s2, s3, shares one copy of numberOfStudents.

For example, we could make a class:

public class Student {
    private String name;

    public static int numberOfStudents = 0;

    public Student(String n) {
        name = n;
        numberOfStudents++;
    }
}

and create a few objects:

Student a = new Student("Alice");
Student b = new Student("Bob");
Student c = new Student("Charlie");

which makes Student.numberOfStudents 3.

Static

We use static to denote that a variable or method belongs to the class itself rather than to an individual object.

This would be an instance variable:

private String name;

and this would be a class variable:

private static int numberOfStudents;

Public and Private

If we want some class variable to be accessible outside of the class, we can declare it as public:

public class Game {
    public static int players = 0;
}

which means we can do:

System.out.println(Game.players); // get # of players
Game.players = 5; // modify # of players

Class Methods

Similarly, we can define a method as static to denote it belongs to a class:

public class MathHelper {

    public static int doubleValue(int x) {
        return x * 2;
    }
}

Now we can call it without creating a MathHelper object:

int result = MathHelper.doubleValue(5);

System.out.println(result); // 10

Class methods can access class variables, other class methods, its parameters, and local variables, but NOT instance variables:

public class Counter {

    private static int count = 0;

    public static void increase() {
        count++;
    }

    public static int getCount() {
        return count;
    }

    public static void reset() {
        count = 0;
    }

    public static void resetAndIncrease() {
        reset();
        increase();
    }
}

We CANNOT do this

public class Student {
    private String name;

    public static void printName() {
        System.out.println(name); // ERROR
    }
}

final Variables

We define a variable as final if we want it to be immutable.

public static final int DAYS_IN_WEEK = 7;

Hacks

Popcorn Hack #1

// CODE_RUNNER: Modify the code so that creating each `Student` automatically increments the shared `numberOfStudents` counter.

public class Student1 {
    private String name;
    public static int numberOfStudents = 0;

    public Student1(String name) {
        this.name = name;
        // TODO: Increment the shared student counter
    }
    
    public static void main(String[] args) {
        Student1 a = new Student1("Alice");
        Student1 b = new Student1("Bob");
        Student1 c = new Student1("Charlie");

        System.out.println(Student1.numberOfStudents); // 3
    }
}

Student1.main(null);

Popcorn Hack #2

// CODE_RUNNER: Fix the code so that `printName()` can still be a `static` method. You might have to change what the method accepts.

public class Student2 {
    private String name;

    public Student2(String name) {
        this.name = name;
    }

    public static void printName() {
        System.out.println(name);
    }

    public static void main(String[] args) {
        Student2 s = new Student2("Alice");
        Student2.printName();
    }
}

Student.main(null);

Homework

In this assignment, you’ll be modifying a partially implemented Java class called BankAccount.

Download and unzip 3-7_bank.zip, which contains a simple Java Maven project. Complete the TODOs listed, and run tests using mvn test.

All Java lessons