ACSA Exam Prep
Unit 3 · Class Creation · Topic 3.7

Class Variables and Methods

Skill 2.CSkill 3.B

Big idea: static means "belongs to the class, not to any one object." A static variable has a single shared copy, which makes it ideal for counters and constants.

Learning objectives
  • Develop code to define behaviors of a class through class methods.
  • Develop code to declare the class variables that belong to the class.

One shared copy

public class Ticket {
  private static int sold = 0;   // one copy, shared
  private int number;            // one per object

  public Ticket() {
    sold++;
    number = sold;
  }

  public int getNumber() { return number; }

  public static int getSold() { return sold; }
}

Watching the shared counter

Code
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
Ticket t3 = new Ticket();
System.out.println(t1.getNumber() + " " + t3.getNumber());
System.out.println(Ticket.getSold());
Output
1 3
3

What static methods can and can't do

  • Static methods can use class variables and call other static methods.
  • They have no this, so they can't use instance variables or call instance methods, unless an object is passed in as a parameter.
  • Constants are often public static final, used as ClassName.NAME, like Integer.MAX_VALUE.
Key points
  • Class variables (static) are shared by all objects: one copy.
  • Public class variables are used from outside as ClassName.variable.
  • Class methods can use class variables and other class methods, but not instance variables.
  • A final variable can't be changed after it is set.
Watch out
  • Using an instance variable inside a static method doesn't compile.
Quick check
Every object of class Car should know how many Cars have been made. What should the counter be?
Show answer
A private static int, incremented in the constructor.