AP Computer Science A · Study guide

Class Methods

Unit 3 · Class Creation · Topic 3.7

Class Methods

What a static method can reach, what it cannot, and the one way to hand it an object anyway.

Exam-day recap
  • A class method belongs to the class itself, not to any particular object; it is marked static.
  • Class methods cannot access instance variables or call instance methods without being passed an instance as a parameter.
  • Class methods can access or change class variables and can call other class methods.
  • The escape hatch: pass the object in as a parameter, then go through it.
  • Call a class method with the class name and the dot operator — no object required.
  • main is static because it runs before any object exists — it is where objects get created.
  • Inside main, referring to an instance variable directly fails to compile; construct an object first.
  • Instance state multiplies, class state does not: many objects share one class variable copy.
  • Instance methods reach everything; class methods reach class-level things only.

1The Error Everyone Meets First

public class Player
{
   private String name;
   private int goals;

   public Player(String name, int goals)
   {
      this.name = name;
      this.goals = goals;
   }

   public static void printGoals()
   {
      System.out.println(goals);   // does not compile
   }
}

The compiler rejects that last line, and the reason is a question rather than a rule: whose goals?

printGoals is a class method — it belongs to Player itself, not to any particular player. There might be a Son object with 14 goals and a Haaland object with 27, or there might be no players at all. The method has no way to know which one goals means, so the code cannot compile.

Drawn in memory the error stops looking like a rule and starts looking like an unanswerable question:

The learning objective

3.7.A — develop code to define behaviors of a class through class methods. Two rules govern everything here: what a class method cannot reach on its own, and what it can.

2The Two Rules

Rule 1 — no instance access without an instance

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.

Rule 2 — class-level access is fine

Class methods can access or change the values of class variables, and can call other class methods.

From inside a class methodAllowed?
Read or write a class variableYes
Call another class methodYes
Read or write an instance variable, bareNo
Call an instance method, bareNo
Use an object it was given as a parameterYes — this is the escape hatch

2.1 The Escape Hatch Is the Point

Rule 1 is usually taught as "static methods can't touch instance variables," which is not what the course says. The full sentence ends with without being passed an instance of the class via a parameter — and that clause is the useful half.

public static void printGoals(Player p)
{
   System.out.println(p.getName() + ": " + p.getGoals());
}

Now it compiles. The question "whose goals?" has an answer — p's. The method still belongs to the class rather than to any object, but it has been handed an object to work on.

Player son = new Player("Son", 14);
Player haaland = new Player("Haaland", 27);

Player.printGoals(son);       // Son: 14
Player.printGoals(haaland);   // Haaland: 27

Compare the two pictures. The class method did not gain a new power; it gained an address:

How to say it correctly

Not "static methods cannot use instance variables" — they can, through an object passed in. The accurate statement is that a class method has no object of its own. Give it one and it works normally; give it none and there is nothing for an instance variable name to refer to.

2.2 Comparing More Than One Object

Class methods are the natural home for anything involving several objects at once, because no single object owns the operation:

public static Player topScorer(Player a, Player b)
{
   if (a.getGoals() >= b.getGoals())
   {
      return a;
   }
   return b;
}

Written as an instance method this would read son.topScorer(haaland), which implies Son is somehow in charge of the comparison. As a class method it reads Player.topScorer(son, haaland) — the class performing an operation on two of its objects, which is what is actually happening.

3Why main Is Static

public static void main(String[] args)

main has to run before any object exists — it is where objects get created. If it were an instance method, something would have to construct an object in order to call it, and nothing has run yet to do the constructing.

The consequence students trip over

Because main is a class method, every rule above applies inside it. Referring to an instance variable directly in main fails to compile, for exactly the reason printGoals() failed. Inside main you must construct an object first and then go through it.

public static void main(String[] args)
{
   // System.out.println(goals);        // no — whose goals?

   Player salah = new Player("Salah", 19);
   System.out.println(salah.getGoals());   // yes — Salah's
}

4Reaching Class-Level Members Freely

Rule 2 is the permissive one. A class method may use anything that also belongs to the class:

public class Player
{
   private static int playerCount = 0;   // class variable
   private String name;                     // instance variable

   public Player(String name)
   {
      this.name = name;
      playerCount++;                        // every new Player bumps the shared count
   }

   public static int getPlayerCount()
   {
      return playerCount;                   // fine — class variable
   }

   public static boolean squadIsFull()
   {
      return getPlayerCount() >= 25;         // fine — calling another class method
   }
}

Both class methods work with no object anywhere in sight, because everything they touch belongs to Player itself.

new Player("Son");
new Player("Haaland");
new Player("Salah");

System.out.println(Player.getPlayerCount());   // 3
System.out.println(Player.squadIsFull());       // false

Three constructions, three frames. Watch which boxes multiply and which one never does:

The single box is the whole idea

Two objects now exist and there are two name boxes — but there was never a second playerCount to create. Each constructor incremented the same box, which is why the second one read 1 before it wrote 2.

Note the call syntax

Player.getPlayerCount() — the class name and the dot operator, because the method belongs to the class. There is no object on the left, and none is needed.

4.1 The Asymmetry Worth Memorizing

DirectionAllowed?Why
Class method → class variableYesBoth belong to the class
Class method → instance variableNo (bare)No object to read it from
Instance method → class variableYesEvery object can see the shared copy
Instance method → instance variableYesIt has an object — its own
One sentence that captures it

Instance methods can reach everything; class methods can only reach class-level things. The restriction runs one way only, and it is not about permission — it is about whether an object exists to ask.

5Reading Code for This

public class Squad
{
   private static int matchesPlayed = 0;
   private String club;

   public Squad(String club)     { this.club = club; }
   public String getClub()       { return club; }

   public static void playMatch()
   {
      matchesPlayed++;              // line 1
      System.out.println(club);    // line 2
      System.out.println(getClub()); // line 3
   }
}
LineVerdictReason
1CompilesmatchesPlayed is a class variable — Rule 2
2Failsclub is an instance variable and no object is present
3FailsgetClub() is an instance method — same reason

The fix for both failures is the same: take a Squad as a parameter and go through it.

public static void playMatch(Squad s)
{
   matchesPlayed++;
   System.out.println(s.getClub());
}

6Check Yourself

A class method needs the name of a specific player. What must change?

Response

It must be passed an instance of the class as a parameter, then read the name through that object. A class method has no object of its own, so "a specific player" has to arrive from outside.

Can an instance method read a class variable?

Response

Yes. The restriction only runs the other way. Every object of the class shares the one copy of a class variable, so any instance method can read or change it — and a change made through one object is visible through all of them.

Why can main not use an instance variable directly?

Response

Because main is itself a class method, so every rule applies inside it. It must construct an object first and access the variable through that object.

Should a method that compares two Player objects be an instance method or a class method?

Response

A class method taking both players as parameters. The operation belongs to no single object — writing it as an instance method would make one of the two players arbitrarily responsible for a comparison that treats them symmetrically.

7Summary

IdeaWhat to remember
Class methodBelongs to the class, not to any object; marked static
Rule 1Cannot reach instance variables or instance methods without an instance passed as a parameter
Rule 2Can reach class variables and call other class methods
The escape hatchPass the object in, then go through it
Calling oneClass name and the dot operator — no object required
mainIs a class method, so all of this applies inside it
The asymmetryInstance methods reach everything; class methods reach class-level only
Good useOperations over several objects, or over none at all
The habit

When a static method will not compile, ask the compiler's question out loud: whose? Whose goals, whose club, whose name. If there is no answer inside the method, the method needs an object handed to it — and that is a parameter, not a keyword.