Skip to main content

Unit 3 · Topic 3.7

3.7 Class Variables and Methods

Some data belongs to a class as a whole, not to any one object. This topic covers static class variables, which every object shares, static class methods, which run without an object, and final, which makes a variable's value permanent.

Key terms

  • class variable
  • class method
  • static
  • final
  • shared copy

Class variables

A class variable is declared with the keyword static. There's only one copy, and it belongs to the class itself. Every object of the class shares it, so a change made through one object is seen by all of them. An instance variable, by contrast, has a separate copy inside every object.

A classic use is counting how many objects have been created: the constructor adds 1 to a static counter every time it runs.

public class Ticket { public static final int MAX_TICKETS = 500; private static int issued = 0; private int number; public Ticket() { issued++; number = issued; } public int getNumber() { return number; } public static int getIssued() { return issued; } public static int ticketsLeft() { return MAX_TICKETS - issued; } }

Each ticket gets its own number (an instance variable), but issued is a single shared count.

Instance versus static

This table sums up the differences.

QuestionInstance variable or methodClass (static) variable or method
How many copies?one per objectone for the whole class
How do you call or use it from outside?through an object, like a.getNumber()through the class name, like Ticket.getIssued()
Can it use instance variables?yesonly through an object passed in
Does it have this?yesno

Accessing static members

A public class variable or class method is used from outside the class with the class name and a dot, as in Ticket.MAX_TICKETS or Ticket.getIssued(). You've already done this with Math.sqrt and Integer.MAX_VALUE.

What class methods can and can't do

A class method is declared static. It can use class variables and call other class methods.

There's no object behind a static method call, so a static method can't use instance variables or call instance methods directly. Whose number would it use? It can only work with an object's data if an object is passed to it as a parameter and it calls methods on that object.

final

A variable declared final can't be changed after it gets its value. Trying to assign to it again is a compile error. Constants like MAX_TICKETS are usually public static final, written in capital letters with underscores. They're safe to make public because nobody can change them.

Worked examples

Try each one yourself first, then open the solution.

  1. Example 1

    A shared counter

    Using the Ticket class above, what does this code print?Ticket a = new Ticket(); Ticket b = new Ticket(); Ticket c = new Ticket(); System.out.println(a.getNumber() + " " + c.getNumber()); System.out.println(Ticket.getIssued() + " " + Ticket.ticketsLeft());

    Show the solution
    1. Step 1: issued starts at 0 and is shared by all tickets.
    2. Step 2: Creating a makes issued 1, and a's own number is 1. Creating b makes issued 2 and gives b number 2. Creating c makes issued 3 and gives c number 3.
    3. Step 3: The first line prints a's and c's numbers: 1 and 3.
    4. Step 4: Ticket.getIssued() returns the shared count, 3, and Ticket.ticketsLeft() is 500 − 3 = 497.

    Answer: Two lines: 1 3, then 3 497.

  2. Example 2

    Which one won't compile?

    Which of these causes a compile error? I. A static method in Ticket that returns number * 2. II. Code in another class that runs Ticket.MAX_TICKETS = 600;. III. A static method in another class that takes two Ticket parameters and returns whether their getNumber() values are equal.

    Show the solution
    1. Step 1: I: number is an instance variable. A static method has no object, so it can't use number directly. Compile error.
    2. Step 2: II: MAX_TICKETS is final, so it can't be assigned a new value. Compile error.
    3. Step 3: III: the method uses objects passed in as parameters and calls their public getNumber() method. That's allowed. It compiles.
    4. Step 4: public static boolean sameNumber(Ticket x, Ticket y) { return x.getNumber() == y.getNumber(); }

    Answer: I and II cause compile errors; III compiles.

Common mistakes

  • Using an instance variable inside a static method. A static method has no object to take it from.
  • Making a counter an instance variable. Then each object counts only itself, and every count stays at 1.
  • Trying to change a final variable after it's set.

On the exam

  • Expect questions that create several objects and ask about a shared static counter. Remember there's only one copy, no matter how many objects exist.
  • On free-response Question 2, use a static variable only if the description says a value is shared by all objects.

Connected topics

Videos

  • AP Computer Science A - Topic 3.7 - Part 1: Class Variables

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Class Variables and Methods

    CodeHSWatch on YouTube (opens in a new tab)

  • Static vs Non-Static Variables and Methods In Java - Full Simple Tutorial

    Coding with JohnWatch on YouTube (opens in a new tab)

  • AP Computer Science A - Topic 3.7 - Part 2: Writing Class Methods

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Java Fields (Class Variables & Instance Variables)*

    Bill BarnumWatch on YouTube (opens in a new tab)

  • Java final keyword ⛔

    Bro CodeWatch on YouTube (opens in a new tab)

Check yourself

4 questions on 3.7 Class Variables and Methods. Pick an answer to see if you got it, and why.

Code
public class Ticket
{
    private static int count = 0;
    private int id;
 
    public Ticket()
    {
        count++;
        id = count;
    }
 
    public int getId()
    {
        return id;
    }
 
    public static int getCount()
    {
        return count;
    }
}
Question 1 of 4

What is printed as a result of executing the following code segment, which appears in a class other than Ticket?Ticket a = new Ticket(); Ticket b = new Ticket(); Ticket c = new Ticket(); System.out.println(a.getId() + " " + c.getId() + " " + Ticket.getCount());

Question 2 of 4

Which of the following methods, if added to the Ticket class, causes a compile-time error?

Question 3 of 4

Consider the following code segment.final int LIMIT = 10; int total = 4; total += LIMIT; LIMIT = 12; System.out.println(total);What is the result of compiling and running the code segment?

Question 4 of 4

Consider the following class.public class Bank { public static final double RATE = 0.05; }Which of the following expressions, appearing in a different class, correctly uses the value of RATE?

0 of 4 answered