3.08 Scope and Access

14 min read • Assignment

1. Reference Guide

Key Topics


Term Definition Example
Scope The region of code where a variable name can be used. inside the { } it was declared in
Local variable Declared inside a method, constructor, or loop body. Dies at the closing brace. int total = 0;
Parameter Declared in a method or constructor header. Lives for the whole body. public void charge(double amount)
Instance variable Declared in the class, outside every method. Visible to the whole class. private double balance;
Shadowing A local or parameter with the same name as a field hides the field. balance = balance;
this The object the method was called on. this.x always means the field. this.balance = balance;
private Only the declaring class can read or write it. private String owner;
public Any class can use it. public double getBalance()
Accessor / Mutator Public methods that read (getter) or change (setter) a private field. getBalance(), charge(4.50)
  • Local variables and parameters cannot have public or private on them
  • Instance variables are usually private; other classes go through accessors and mutators

Where Each Variable Lives

Variable Type Declared In Accessible In public/private Allowed?
Instance variable Inside the class, outside methods Everywhere in the class Yes (usually private)
Parameter The method/constructor header Only inside that method/constructor No
Local variable Inside a method or loop body Only inside that specific block No

Reading Code on the Exam

  • Name used after a closing brace? → compile error
  • Parameter or local spelled like a field? → the field is shadowed, look for this.
  • name = name; in a constructor? → compiles, but the field stays null or 0
  • int score = 0; inside a method when score is a field? → a new local, the field never changes
  • Another class touching a private field directly? → compile error

2. LxD Cycle Process

Empathize: Students resolve a variable by its spelling, not by where it was declared. They write name = name; in a constructor, see null printed, and blame the print statement, because the assignment “obviously” happened. They also try to print a loop counter after the loop and are surprised the compiler has never heard of it. Research on novice misconceptions finds the same pattern: students carry a fuzzy model of what a declaration does and where a variable exists (Kaczmarczyk et al., 2010).

Define:

  • POV: CSA students need to read code braces first, then names, because two variables can share a spelling while living in different blocks, and a wrong guess about which one is meant produces silent bugs the compiler will not catch.
  • Learning Goal: Students will classify a variable as local, parameter, or instance from its declaration, predict out-of-scope compile errors, repair a shadowed field with this, and use private fields with public accessors and mutators.

Ideate:

  • HMW Question: How might we make an invisible name lookup visible, so a student sees which balance a line is talking about?
  • HMW Question: How might we show that private is what makes a mutator’s validation impossible to skip?
  • Activity: Trace a scope map of one class, run a broken-then-fixed constructor pair where the only difference is this., then fix a class that hides all three traps at once.

Prototype:

  • A reference guide, runnable Java examples, a three-trap repair exercise, an MCQ knowledge check, and a scaffolded grading rubric.
  • Students revise their fixes after reading compiler output or the runner’s printed values.
  • Excellence means explaining which variable each line touches and why, not only producing a class that prints the right answer.

Test:

  • Ask peers in peer review to complete the practice without additional explanation.
  • Observe whether peers locate the declaration before deciding what a name means.
  • Compare your lesson with another that is posted.
  • Use the findings to revise any instruction or rubric criterion that did not guide students clearly.
  • On submission, collect evidence from runner output, MCQ results, AI grading and student explanations.
  • After teaching, grading and analysis, come back and revise lesson to complete teaching cycle for continuous improvement.

3. College Board Requirements

AP CSA Unit 3, Topic 3.8 Scope and Access. Paraphrased from the course and exam description (College Board, 2025):

  • 3.8.A.1 Local variables can be declared in the body of constructors and methods. They may only be used within that constructor or method and cannot be declared public or private.
  • 3.8.A.2 When a local variable has the same name as an instance variable, the name refers to the local variable, not the instance variable.
  • 3.8.A.3 Formal parameters and variables declared in a method or constructor can only be used within that method or constructor.

The College Board tests this topic almost entirely through “what is printed” and “which line does not compile” questions, so the practice below is built around tracing rather than writing new classes.


4. Lesson Plan

Learning Objective: Determine where a variable can be used, recognize when a local variable shadows an instance variable, and access private fields correctly from other classes.

Success Criteria: You can name a variable’s scope from its declaration, fix a shadowing bug with this, and explain why a private field needs public accessors and mutators.

Tech Talk (5 minutes)

Every variable lives inside a pair of braces. Step outside them and the name is gone.

Read code by asking two things: where was this name declared, and is there a closer declaration with the same spelling?

Code Runner Challenge

Predict all three printed lines first, then run it. Then uncomment the println(i) line and read the compiler message.

View IPYNB Source
public class IDCard {
    private double balance;                 // instance variable: the whole class sees it

    public IDCard(double balance) {         // parameter: this constructor only
        this.balance = balance;             // this.balance = the field, balance = the parameter
    }

    public void chargeMonth(int days) {
        double total = 0;                   // local: the rest of this method
        for (int i = 0; i < days; i++) {    // i: the loop only
            total += 2;
        }
        balance -= total;                   // no local named balance here, so this is the field
    }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

5. Code Examples

A. Scope and shadowing. The IDCard class shows which braces each variable lives in

Three things get mixed up a lot:


for (int i = 0; i < 3; i++) { }   // i is gone after this brace
System.out.println(i);             // compile error

balance = balance;                 // parameter assigned to itself, the field is untouched
this.balance = balance;            // the field is assigned

Terminology:

A local variable is destroyed when its block ends. A parameter is a local that lives for the whole method. A parameter or local that shadows a field hides it, and only this. can reach the field again.


Code Runner Challenge

Run it, then uncomment card.balance = 1000000; and see what the compiler says

View IPYNB Source
// CODE_RUNNER: Predict all three printed lines first, then run it. Then uncomment the println(i) line and read the compiler message.
// Scope and Shadowing Examples
public class IDCard {
    // Instance variables: visible in every method of this class
    private String owner;
    private double balance;

    // Step 1: A constructor with parameters that shadow the fields
    public IDCard(String owner, double balance) {
        this.owner = owner;        // this.owner = the field, owner = the parameter
        this.balance = balance;
    }

    // Step 2: A method with a parameter, a local, and a loop variable
    public void chargeMonth(double perDay, int days) {
        double total = 0;                        // local: lives until the method returns
        for (int i = 0; i < days; i++) {         // i: lives only inside the loop
            double fee = perDay + (i * 0.25);    // fee: lives only inside this iteration
            total += fee;
        }
        // System.out.println(i);                // COMPILE ERROR: i is out of scope here
        balance -= total;                        // the field: no local named balance in this method
    }

    // Step 3: A shadowing bug -- the field never changes
    public void refundBroken(double amount) {
        double balance = this.balance + amount;  // declares a NEW local named balance
    }

    // Step 4: The same method, fixed
    public void refund(double amount) {
        balance = balance + amount;              // no local named balance, so this is the field
    }

    public String getOwner() { return owner; }
    public double getBalance() { return balance; }

    public static void main(String[] args) {
        IDCard card = new IDCard("Maya", 50.00);
        card.chargeMonth(2.00, 3);
        System.out.println(card.getOwner() + " after charges: " + card.getBalance());

        card.refundBroken(5.00);
        System.out.println("after refundBroken: " + card.getBalance());   // unchanged

        card.refund(5.00);
        System.out.println("after refund: " + card.getBalance());         // + 5.0
    }
}
IDCard.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

B. Access modifiers. The Kiosk class shows what private lets another class do

Common access mistake:


card.balance = 1000000;          // compile error: balance has private access in IDCard
card.charge(4.50);               // allowed: a public mutator that checks the amount

Terminology:

private means only IDCard can touch balance. Everyone else goes through accessors (getBalance) and mutators (charge), so the checks inside charge cannot be skipped.


Code Runner Challenge

Fix the three bugs without renaming anything, then run it. Expect: Maya 3

View IPYNB Source
// CODE_RUNNER: Run it, then uncomment card.balance = 1000000; and see what the compiler says
// Private Fields and Public Accessors / Mutators
public class IDCard {
    private String owner;
    private double balance;

    public IDCard(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    public String getOwner() { return owner; }       // accessor
    public double getBalance() { return balance; }   // accessor

    public boolean charge(double amount) {           // mutator with a guard
        if (amount <= 0 || amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }
}

public class Kiosk {
    public static void main(String[] args) {
        IDCard card = new IDCard("Maya", 10.00);
        System.out.println("coffee: " + card.charge(4.50) + " -> " + card.getBalance());
        System.out.println("laptop: " + card.charge(999.00) + " -> " + card.getBalance());

        // This would cause an error:
        // card.balance = 1000000;   // NOT ALLOWED: balance has private access in IDCard
    }
}

Kiosk.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

6. Hacks & Practice Tasks

Prepare your submission IPYNB

  1. Create a new notebook in your portfolio homework area: _notebooks/homework.
  2. Add one raw cell at the top with the frontmatter:

Code Runner Challenge

Fill in the blanks, then run it

View IPYNB Source
---
layout: post
codemirror: true
title: Scope and Access HW
categories: [Java]
lesson_language: Java
lesson_topic: Scope-and-Access HW
lesson_part: interactive
lesson_type: lesson
permalink: /csa/unit_03/3_8-hw
author: yourGithubID
---
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
  1. Add code cells for the Popcorn Hack and the Homework Hack. Make sure every cell runs with visible output.
  2. Submit the link to your published page at the bottom of this page, and paste this in the description box:
Lesson: CSA 3.8 Scope and Access
MCQ 3.8: <paste the copied result line, such as 3/4 | answers: C,B,C,B>
Popcorn: Locker prints "Maya 3" after fixing three bugs (yes/no)
Popcorn: one sentence per bug naming which variable the broken line touched
Homework: Player has private fields, a constructor using this, and a guarded mutator (yes/no)
Homework: printed output = <paste the four lines>

Submission Safety Rules (Read First)

  • One class per cell, ending with ClassName.main(null);.
  • Run each cell and leave the output showing.
  • Use your own values, not the sample answer.
  • Include your MCQ score.
  • Use ## headings or smaller.

Popcorn Hack (In-Class)

2-minute challenge: Locker has all three traps in it. Fix each one so the program prints Maya 3, without renaming any variable.

  1. The constructor assigns a parameter to itself
  2. store re-declares the field as a local
  3. A commented-out line would use a loop variable after the loop (leave it commented and explain why)

After it prints Maya 3, add a comment above each fixed line saying which variable the broken version touched.

// CODE_RUNNER: Fix the three bugs without renaming anything, then run it. Expect: Maya 3
// Practice #1 - Try it yourself first!
public class Locker {
    private String owner;
    private int items;

    public Locker(String owner) {
        owner = owner;                 // Bug 1: which owner is on each side of the = ?
        items = 0;
    }

    public void store(int count) {
        int items = this.items;        // Bug 2: is this the field or a new variable?
        for (int i = 0; i < count; i++) {
            int added = 1;
            items += added;
        }
        // System.out.println(added);  // Bug 3: why can this line never compile? Leave it commented.
    }

    public String getOwner() { return owner; }
    public int getItems() { return items; }

    public static void main(String[] args) {
        Locker l = new Locker("Maya");
        l.store(3);
        System.out.println(l.getOwner() + " " + l.getItems());
    }
}

Locker.main(null);

MCQ Check

4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.

Homework Hack

Task: Build a Player class for a game. Store the name and score as private fields, write a constructor whose parameters have the same names as the fields (so you must use this), write a getScore accessor, and write an addPoints mutator that rejects negative amounts. Then, from a separate Game class, try to change the score both ways and print the results.

Solution Skeleton:

// CODE_RUNNER: Fill in the blanks, then run it
public class Player {
    // 1. Two private fields: name (String) and score (int)

    // 2. Constructor: parameters must be named name and score, so use this.
    public Player(String name, int score) {

    }

    // 3. Accessor for score
    public int getScore() {
        return 0;
    }

    // 4. Mutator: add points only if amount > 0, return whether it was accepted
    public boolean addPoints(int amount) {
        return false;
    }
}

public class Game {
    public static void main(String[] args) {
        Player p = new Player("Maya", 10);
        System.out.println("start: " + p.getScore());              // 10
        System.out.println("add 5: " + p.addPoints(5));            // true
        System.out.println("add -50: " + p.addPoints(-50));        // false
        System.out.println("end: " + p.getScore());                // 15
        // p.score = 9999;   // 5. Uncomment once: what does the compiler say? Then comment it again.
    }
}

Game.main(null);

Grading Plan (1 Point Total)

Part Points What earns the points
Popcorn 0.2 Locker prints Maya 3, no variable was renamed, and each fix has a comment naming the variable the broken line touched.
MCQ 0.2 4 correct. 0.15 for 3, 0.1 if every question was answered.
Homework: private fields 0.15 name and score are private.
Homework: constructor 0.15 Parameters share the field names and both fields are set with this.
Homework: accessor and mutator 0.15 getScore returns the field and addPoints rejects amounts that are not positive.
Homework: output 0.15 The four printed lines are 10, true, false, 15, and the p.score line is explained in a comment.
Total 1.0  

Quick Validation Checklist

  • Each cell ends with ClassName.main(null); and shows output.
  • MCQ score in the notes.
  • No this.-less self-assignment left in any constructor.
  • Fields are private and only reached through public methods from Game.

7. Lesson Revisions

Revision Made: Lesson authors: what you changed because of it.


8. Feedback Evidence

Feedback Received: Lesson authors: what your peers said in the practice run.


9. References

College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf

Kaczmarczyk, L. C., Petrick, E. R., East, J. P., & Herman, G. L. (2010). Identifying student misconceptions of programming. In Proceedings of the 41st ACM Technical Symposium on Computer Science Education (pp. 107–111). Association for Computing Machinery.

Oracle. (n.d.). Using the this keyword. The Java Tutorials. https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Oracle. (n.d.). Controlling access to members of a class. The Java Tutorials. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Submit Assignment

Your code will be saved as a Gist and reviewed automatically. You must be logged in to submit.

Need to update a submission later? Open the submissions dashboard.

Course Timeline