AP Computer Science A · Study guide

Scope and Shadowing

Unit 3 · Class Creation · Topic 3.8

Scope and Shadowing

Where a name is visible, and what happens when two things share one — including the constructor that compiles, runs, and quietly does nothing.

Exam-day recap
  • 3.8.A: two ideas — scope, which is where a name is visible, and shadowing, what happens when a local name and instance variable collide.
  • A local variable is declared in the headers or bodies of blocks and can only be accessed in the block where it is declared.
  • Parameters to constructors or methods are also considered local variables.
  • Local variables cannot be declared public or private; a local variable has no outside for an access modifier to govern.
  • Shadowing: when a local variable or parameter shares an instance variable's name, the name refers to the local variable within that body.
  • The classic bug: number = number; assigns the parameter to itself, compiles fine, and leaves the instance variable at its default.
  • Fix a name collision with this.number = number; — this. names the instance variable while bare number is the parameter.
  • Shadowing governs reads too: return count; returns the parameter, not the field.
  • A variable declared in a loop header is local to that loop; using it after the loop is a compile-time error.

1A Constructor That Does Nothing

public class Locker
{
   private int number;
   private String owner;

   public Locker(int number, String owner)
   {
      number = number;
      owner = owner;
   }
}

This compiles without a warning. It runs without an error. Every Locker you create has number 0 and owner null.

Nothing is misspelled and no logic is wrong. The two assignments simply do not touch the instance variables — and understanding exactly why is this entire topic.

The learning objective

3.8.A — explain where variables can be used in the code. Two ideas: scope, which is where a name is visible, and shadowing, which is what happens when a local name and an instance variable collide.

2Blocks and Local Variables

Definition

Local variables are variables declared in the headers or bodies of blocks of code. A local variable can only be accessed in the block in which it is declared.

A block is a region delimited by braces. Method bodies, constructor bodies, loop bodies, and the bodies of if statements are all blocks — and each one is a boundary for the names declared inside it.

public void report()
{
   int total = 0;              // visible for the whole method body

   for (int i = 0; i < 5; i++)
   {
      int doubled = i * 2;      // visible only inside the loop body
      total += doubled;
   }

   // i and doubled are both gone here
   System.out.println(total);   // total is still fine
}
The loop header counts as part of the loop

i is declared in the loop's header, and the essential knowledge says local variables are those declared in headers or bodies. So i is local to the loop and does not exist after it. Code that uses i below the loop does not compile — and this is a favorite exam error to spot.

2.1 Parameters Are Local Variables

The course is explicit: since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables.

public void deposit(double amount)
{
   balance += amount;      // amount is a local variable of this method
}
// amount does not exist out here

That single fact explains the broken constructor at the top, and it is worth holding onto: a parameter is not something special. It is a local variable that happens to receive its initial value from the caller.

2.2 Local Variables Cannot Be public or private

The essential knowledge states this directly, and it makes sense once scope is clear:

public void run()
{
   private int count = 0;   // does not compile
}
Why the rule exists

public and private control access from outside. A local variable has no outside — it cannot be reached from beyond its block by any means, so there is nothing for an access modifier to govern. Instance variables need them; local variables cannot have them.

Instance variableLocal variable
DeclaredIn the class body, outside any methodIn a block header or body
VisibleThroughout the classOnly within its block
LifetimeAs long as the objectUntil the block ends
public/privateYes — normally privateNot allowed
Default valueYes — 0, false, nullNo — must be assigned before use

3Shadowing

The rule

When there is a local variable or parameter with the same name as an instance variable, the variable name refers to the local variable instead of the instance variable within the body of that constructor or method.

The local name wins. Not the instance variable, and not "whichever was declared first" — the local one, every time, inside that body.

3.1 Back to the Broken Constructor

public Locker(int number, String owner)
{
   number = number;    // parameter = parameter
   owner = owner;      // parameter = parameter
}

Inside this constructor the name number refers to the parameter, on both sides of the assignment. The statement copies the parameter into itself, which changes nothing. The instance variable is never mentioned, so it keeps its default: 0 for the int, null for the String.

Why nothing warns you

number = number; is perfectly legal Java. Assigning a variable to itself is pointless but not an error, so the compiler has nothing to complain about. This bug is invisible until an object comes out wrong — which is why the exam tests it by inspection rather than by output.

3.2 Three Ways to Fix It

Rename the parameter so no collision exists:

public Locker(int lockerNumber, String lockerOwner)
{
   number = lockerNumber;
   owner = lockerOwner;
}

Keep the names and disambiguate — the usual professional choice:

public Locker(int number, String owner)
{
   this.number = number;
   this.owner = owner;
}

Do not shadow at all where the method has no reason to:

public void renumber(int newNumber)
{
   number = newNumber;   // no collision, so no ambiguity
}
Reading the middle version

this.number is unambiguously the instance variable; bare number is the parameter. So the statement reads "the object's number becomes the value passed in." Shadowing is only a bug when it is unintended — done deliberately with this, it is the standard way to write a constructor.

3.3 Shadowing Applies to Reads Too

private int count = 10;

public int report(int count)
{
   return count;      // the parameter, not the field
}

Called as report(3), this returns 3 — never 10. The rule is about which variable the name refers to, so it governs reading exactly as it governs assignment.

4Tracing Scope

Work outward from the innermost block. A name is visible if it was declared in the current block or in a block enclosing it.

public class Tally
{
   private int total;                 // A: whole class

   public void add(int[] values)      // B: whole method
   {
      int skipped = 0;              // C: whole method body

      for (int v : values)          // D: the loop
      {
         if (v < 0)
         {
            int flagged = v;         // E: this if-block only
            skipped++;
         }
         total += v;
      }
   }
}
NameDeclared inVisible
totalClass body (instance variable)Every method in the class
valuesMethod header (parameter)The whole method body
skippedMethod bodyFrom its declaration to the end of the method
vLoop headerThe loop body only
flaggedThe if blockThat block only — not the rest of the loop
Two failures this table predicts

Using flagged after the if closes does not compile. Using v after the loop does not compile. Both look reasonable on the page, and both are compile-time errors rather than wrong answers — which is what the question is usually asking you to identify.

4.1 Declaring Inside a Loop Resets Every Pass

for (int i = 0; i < 3; i++)
{
   int sum = 0;      // a NEW sum each pass
   sum += i;
   System.out.print(sum + " ");
}

Prints 0 1 2, not 0 1 3. The declaration is inside the block, so each iteration creates a fresh sum initialized to 0. Moving the declaration above the loop is what makes an accumulator accumulate — and that one-line move is the difference between the two outputs.

5Check Yourself

A method takes a parameter score and the class has an instance variable score. Inside the method, what does the bare name score refer to?

Response

The parameter. When a local variable or parameter shares a name with an instance variable, the name refers to the local one within that body. Reaching the instance variable requires this.score.

Does private int temp = 0; inside a method body compile?

Response

No. Local variables cannot be declared public or private. Access modifiers govern visibility from outside the class, and a local variable has no outside — it is unreachable beyond its block by construction.

Why does the broken Locker constructor leave owner as null rather than failing?

Response

Because the instance variable was never assigned, so it keeps the default value it received when the object was created — null for a reference type. The constructor's two statements only ever touched the parameters. Nothing failed; the work simply went nowhere.

A loop declares int i in its header. Can the method return i after the loop ends?

Response

No — it is a compile-time error. Variables declared in a loop header are local to that loop, and the name does not exist after it. If the value is needed later, declare the variable before the loop instead.

6Summary

IdeaWhat to remember
Local variableDeclared in a block's header or body; usable only in that block
ParametersAre local variables of their method or constructor
Access modifiersLocal variables cannot be public or private
DefaultsInstance variables get one; local variables do not
ShadowingA local name with the same name as an instance variable wins inside that body
Applies toReads and assignments alike
The classic bugnumber = number; assigns the parameter to itself and compiles fine
Loop headersDeclare local variables; the name is gone after the loop
The habit

When a constructor or setter takes a parameter named after a field, write this. on the left side before you write anything else. And when an object comes out with 0 and null where real values should be, look at the constructor's assignments before looking anywhere else — that pattern is nearly always shadowing.