Unit 3 · 18 min

3.7 Class Variables and Methods

Instance data lives in each object; class data lives once, in the class.

Summary, objectives and course and exam description (CED) codes

A class variable is declared with the static keyword and belongs to the class, so all objects share a single copy. Class methods can use class variables and call other class methods, but they cannot use instance variables or instance methods unless an object is passed in as a parameter. A variable declared final cannot be changed.

By the end of this session you can

  • 3.7.A Develop code to define behaviors of a class through class methods.
  • 3.7.B Develop code to declare the class variables that belong to the class.

3.7.A3.7.A.13.7.A.23.7.B3.7.B.13.7.B.23.7.B.3

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. Class variables: one shared copy

Class variables belong to the class, and all objects of the class share a single copy. They are marked with the keyword static before the variable type 3.7.B.1. Instance variables are the opposite: each object has its own copy.

This class is used on the whole page:

public class Ticket
{
    public static final int MAX_TICKETS = 100;   // class variable, final
    private static int nextNumber = 1;           // class variable

    private String event;                        // instance variable
    private int number;                          // instance variable

    public Ticket(String eventName)
    {
        event = eventName;
        number = nextNumber;
        nextNumber++;
    }

    public int getNumber()
    {
        return number;
    }

    public static int ticketsIssued()
    {
        return nextNumber - 1;
    }

    public static int ticketsLeft()
    {
        return MAX_TICKETS - ticketsIssued();
    }

    public static boolean isEarlier(Ticket a, Ticket b)
    {
        return a.number < b.number;
    }

    public String toString()
    {
        return event + " #" + number;
    }
}
Ticket t1 = new Ticket("Concert");
Ticket t2 = new Ticket("Concert");
Ticket t3 = new Ticket("Match");
System.out.println(t1 + ", " + t2 + ", " + t3);
System.out.println(Ticket.ticketsIssued());

Output:

Concert #1, Concert #2, Match #3
3

Memory after the code runs:

class Ticket:   MAX_TICKETS 100   nextNumber 4     (one copy, shared)

t1 [ ref ] ---> Ticket object: event "Concert"  number 1
t2 [ ref ] ---> Ticket object: event "Concert"  number 2
t3 [ ref ] ---> Ticket object: event "Match"    number 3

Printing a Ticket uses its toString method (background only: writing toString is outside the AP® exam). Every constructor call read and changed the same nextNumber. That is how each ticket gets a different number.

2. Using a public class variable from outside

A class variable that is public is accessed outside the class with the class name and the dot operator, because it is associated with the class, not with objects of the class 3.7.B.2. This is a new program, so no tickets exist before it runs:

System.out.println("Limit: " + Ticket.MAX_TICKETS);
Ticket t = new Ticket("Play");
System.out.println("Left: " + Ticket.ticketsLeft());

Output:

Limit: 100
Left: 99

You do not need any Ticket object to read Ticket.MAX_TICKETS. A private class variable such as nextNumber cannot be used from outside at all: other classes use the public class method ticketsIssued instead.

3. final: a value that cannot change

When a variable is declared final, its value cannot be modified 3.7.B.3. Constants are usually public static final, with a name in capital letters.

Ticket.MAX_TICKETS = 500;

Compiler says:

error: cannot assign a value to static final variable MAX_TICKETS

final works for local variables too:

final double TAX_RATE = 0.08;
double price = 50.0;
System.out.println(price + price * TAX_RATE);

Output:

54.0

4. What class methods can do

A class method (a static method) can access or change the values of class variables, and it can call other class methods 3.7.A.2.

In Ticket, the class method ticketsIssued reads the class variable nextNumber, and the class method ticketsLeft calls the class method ticketsIssued. A class method can also change a class variable:

public class Scoreboard
{
    private static int games = 0;
    private static int totalGoals = 0;

    public static void recordGame(int goals)
    {
        games++;
        totalGoals += goals;
    }

    public static double averageGoals()
    {
        return (double) totalGoals / games;
    }

    public static String report()
    {
        return games + " games, " + averageGoals() + " goals per game";
    }
}
Scoreboard.recordGame(3);
Scoreboard.recordGame(0);
Scoreboard.recordGame(2);
System.out.println(Scoreboard.report());

Output:

3 games, 1.6666666666666667 goals per game

5. What class methods cannot do (without an object)

Class methods cannot access or change instance variables, or call instance methods, unless an instance of the class is passed to them through a parameter 3.7.A.1. A class method is called on the class, so there is no “current object” whose instance variables it could use.

public class Seat
{
    private int row;

    public Seat(int r)
    {
        row = r;
    }

    public static boolean isFrontRow()
    {
        return row == 1;
    }
}

Compiler says:

error: non-static variable row cannot be referenced from a static context

The fix is to pass an object in. Ticket.isEarlier does exactly that: it receives two Ticket objects and uses their instance variables.

Ticket a = new Ticket("Concert");
Ticket b = new Ticket("Concert");
System.out.println(Ticket.isEarlier(a, b));
System.out.println(Ticket.isEarlier(b, a));

Output:

true
false

Calling an instance method from a class method without an object fails the same way:

public class Clock
{
    private int minutes;

    public int getMinutes()
    {
        return minutes;
    }

    public static int getHours()
    {
        return getMinutes() / 60;
    }
}

Compiler says:

error: non-static method getMinutes() cannot be referenced from a static context
Can use instance variables and instance methods? Can use class variables and class methods?
Instance method Yes Yes
Class method Only through an object parameter 3.7.A.1 Yes 3.7.A.2

Lock it in: memory hooks

  • staticstatic = stays with the class. One copy on the class, none in the objects.
  • Class methodsA class method has no object in hand. Want instance data? Hand it an object.
  • finalfinal = finished. Once it has a value, it keeps it.

Common misconceptions

  • "Each object gets its own copy of a static variable."

    Not quite. A static (class) variable belongs to the class. There is exactly one copy, and every object of the class shares it, so a change made through one object is seen by all.

  • "A static method can use any instance variable of its class."

    Not quite. A class method is not called on an object, so there is no instance variable to use. It can only reach instance data through an object passed to it as a parameter.

  • "final means the variable is private."

    Not quite. final means the value cannot be modified after it is set. Access is a separate choice: a final variable can be public or private.

Exam traps

  • Counting objects: a static counter incremented in the constructor counts every object ever created, across all variables.
  • Inside a static method, a bare instance variable name is a compile error: non-static variable cannot be referenced from a static context.
  • Assigning to a final variable after it is set does not compile.
  • Instance methods CAN use class variables; it is only class methods that cannot use instance variables.

2PracticeRecall it, then check yourself

In 30 seconds

  1. Class variables belong to the class; all objects share a single copy; declared with static before the type.
  2. A public class variable is used outside the class as ClassName.variableName.
  3. A final variable cannot be modified after it gets its value.
  4. Class methods can access and change class variables and call other class methods.
  5. Class methods cannot use instance variables or call instance methods unless an object is passed in as a parameter.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Class Variables and Methods

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.7.B.1
    public class Visitor
    {
        private static int count = 0;
        private int id;
    
        public Visitor()
        {
            count++;
            id = count;
        }
    
        public int getId()
        {
            return id;
        }
    
        public static int getCount()
        {
            return count;
        }
    }
    
    Visitor v1 = new Visitor();
    Visitor v2 = new Visitor();
    Visitor v3 = v2;
    Visitor v4 = new Visitor();
    System.out.println(v1.getId() + " " + v3.getId() + " " + Visitor.getCount());
    Show answer

    Answer: C. count is a class variable, so all objects share one copy and it counts constructor calls. Only three objects are created: v3 = v2 copies a reference and does not call the constructor, so the count is 3 and v3 has the same id as v2, which is 2. The option 1 2 4 counts v3 as a new object, and 3 3 3 treats id as if it were shared too.

  2. 2 Consider the following incomplete class. The class method area is intended to return the area of the rectangle passed to it. Which of the following can replace /* missing code */ so that area works as intended? 3.7.A.1
    public class Rectangle
    {
        private int width;
        private int height;
    
        public Rectangle(int w, int h)
        {
            width = w;
            height = h;
        }
    
        public static int area(Rectangle r)
        {
            /* missing code */
        }
    }
    Show answer

    Answer: A. A class method cannot use instance variables without an object, but here an object is passed in as r, and because area is inside Rectangle it may read r's private variables. Using width alone, or this, does not compile in a static method because there is no current object. Rectangle has no getArea method.

  3. 3 A class Game contains the declaration public static final int MAX_LEVEL = 10;. Which of the following statements, appearing in a method of another class, compiles without error? 3.7.B.2, 3.7.B.3
    public class Game
    {
        public static final int MAX_LEVEL = 10;
    }
    Show answer

    Answer: D. A public class variable is accessed outside its class with the class name and the dot operator, exactly as declared: Game.MAX_LEVEL. It is final, so assigning 12 to it does not compile. Java is case-sensitive, so maxLevel is a different, undeclared name, and without Game. the other class cannot find MAX_LEVEL.

  4. 4 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.7.A.2
    public class Tally
    {
        private static int total = 0;
    
        public static void add(int n)
        {
            total += n;
        }
    
        public static void addTwice(int n)
        {
            add(n);
            add(n);
        }
    
        public static int getTotal()
        {
            return total;
        }
    }
    
    Tally.add(5);
    Tally.addTwice(3);
    Tally.add(-2);
    System.out.println(Tally.getTotal());
    Show answer

    Answer: B. Class methods can change class variables and call other class methods. total becomes 5, then addTwice(3) calls add twice to reach 11, then add(-2) gives 9. The option 6 counts addTwice as one addition, 11 forgets the last call, and 0 wrongly assumes that class methods cannot change the class variable.

  5. 5 The following method is written inside a Player class that has the instance variable private int score;. Which of the following best describes the result? 3.7.A.1
    public static void reset()
    {
        score = 0;
    }
    Show answer

    Answer: D. A class method is not called on an object, so it has no instance variable named score to change, and the compiler reports that a non-static variable cannot be referenced from a static context. A static method does not loop over all objects or pick one, and the problem is found at compile time, not at run time. Passing a Player parameter, such as p.score = 0;, would fix it.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Class variabletap to flip

    An attribute declared with the keyword static that belongs to the class, so all objects of the class share a single copy.

    Example and CED codes
  • finaltap to flip

    A keyword that makes a variable's value unchangeable once it has been set.

    Example and CED codes
  • Instance variabletap to flip

    An attribute declared in a class outside any method or constructor, whose value is unique to each object of the class.

    Example and CED codes
  • Methodtap to flip

    A named block of code that only runs when it is called.

    Example and CED codes
  • Classtap to flip

    The formal implementation, or blueprint, of the attributes and behaviors of an object. A class defines a reference type.

    Example and CED codes
  • Objecttap to flip

    A specific instance of a class with defined attributes.

    Example and CED codes
  • Parametertap to flip

    A variable declared in the header of a method or constructor. It receives the value passed in and can be used in the body.

    Example and CED codes

Questions students ask

What is a static variable in Java?

A static variable, or class variable, belongs to the class instead of to any one object. All objects of the class share a single copy, so it is often used for counters and shared settings.

Why can't a static method use instance variables?

A static method is called on the class, not on an object, so there is no current object whose instance variables it could use. Pass an object as a parameter and use it, such as a.getNumber().

How do you access a public static variable from another class?

Use the class name and the dot operator, such as Ticket.MAX_TICKETS, because the variable is associated with the class, not with objects of the class.

What does final mean for a variable?

A final variable cannot be modified once it has a value. Constants such as public static final int MAX_TICKETS = 100; are written with final.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure