Class Design & Encapsulation - Complete Interactive Lesson
Part 1: Core Concepts
🏛️ Class Design
Part 1 of 7 — Static vs Instance, Scope, and Method Design
Static vs Instance
| Feature | Instance | Static |
|---|---|---|
| Belongs to | Each object | The class itself |
| Access | object.method() | ClassName.method() |
| Can access | Instance + static members | Static members directly; instance members only through an object reference |
| Keyword | (none) | static |
| Example | s.length() | Math.sqrt(16) |
public class Counter {
private static int totalCount = 0; // Shared by ALL Counter objects
private int myCount = 0; // Unique to each Counter object
public Counter() {
totalCount++;
}
public void increment() {
myCount++;
}
public static int getTotalCount() {
return totalCount; // OK - static method accessing static variable
// return myCount; // ERROR - no current object here, so the bare name myCount has no meaning
}
}
🔑 Static variables are shared across all instances of a class. Changing it in one place changes it everywhere. Great for counting objects or shared constants.
⚠️ A static method has no
this, so it cannot use an instance variable by its bare name. It can reach instance data through an object reference it is given or creates, for examplec.myCountfor a Countercpassed in as a parameter.
Concept Check 🎯
Variable Scope
| Scope | Where Declared | Where Accessible |
|---|---|---|
| Instance variable | In the class, outside methods | Throughout the entire class |
| Local variable | Inside a method or block | Only within that method/block |
| Parameter | In method signature | Only within that method |
| Loop variable | In for/while loop header | Only within that loop |
public class Example {
private int x = 10; // Instance: accessible everywhere in class
public void demo(int y) { // Parameter: accessible in demo()
int z = 20; // Local: accessible in demo()
for (int i = 0; i < 5; i++) { // Loop var: accessible in loop only
// x, y, z, and i are all accessible here
}
// i is NOT accessible here
}
// y and z are NOT accessible here
}
Method Design Principles
| Principle | Description |
|---|---|
| Single responsibility | Each method should do one thing well |
| Parameters | Pass in what the method needs; avoid accessing global state |
| Return values | Return computed results rather than printing them |
| Method overloading | Multiple methods with same name but different parameters |
Applied Recall ✍️
-
A variable declared with the static keyword is shared by all _______ of the class.
-
A variable declared inside a method is called a _______ variable and exists only while that method runs.
-
Having multiple methods with the same name but different parameter lists is called method _______.
Classify the Concept 🔍
AP Exam Strategy: Class Design
- Know the difference between static and instance — this determines how you call methods and access data
- Scope questions test whether a variable is accessible in a given context
- A static method has no
this: it cannot use instance variables by their bare names, but it can reach them through an object reference (c.myCount) - Overloading: same name, different parameter lists. A different return type alone does not make a legal overload
- FRQ tip: when designing a class, always start with private instance variables, then write the constructor(s), then methods
AP-Style Application 🎯
Part 2: Static Variables and Methods in Depth
🏛️ Class Design
Part 2 of 7 — Static Variables and Methods in Depth
Part 1 compared static and instance members in a table. This part traces them (CED Topic 3.7): how one shared variable changes as objects are created and used, how constants work, and exactly what a static method may refer to.
| In this part |
|---|
| One shared copy: tracing static and instance state together |
static final constants |
| What a static method can and cannot reference |
| Worked example: a team total shared by every player |
One Copy for the Whole Class
A class variable (declared static) belongs to the class. There is exactly one copy, no matter how many objects exist, and every object reads and writes that same copy. An instance variable gives every object its own copy.
public class Ticket {
public static final int LIMIT = 500;
private static int nextNumber = 100;
private static int issued = 0;
private int number;
public Ticket() {
number = nextNumber;
nextNumber++;
issued++;
}
public int getNumber() {
return number;
}
public static int getIssued() {
return issued;
}
}
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
| After | nextNumber (shared) | issued (shared) | a.number | b.number | c.number |
|---|---|---|---|---|---|
| class is loaded | 100 | 0 | |||
new Ticket() for a | 101 | 1 | 100 | ||
new Ticket() for b | 102 | 2 | 100 | 101 | |
new Ticket() for c | 103 | 3 | 100 | 101 | 102 |
- The initializers
= 100and= 0on the static variables run once, when the class is loaded, not on everynew. - Each constructor call copies the shared counter into the new object's own
number, then advances the counter. This is the standard way to give objects unique IDs. Ticket.getIssued()returns 3. Client code calls a static method with the class name.
Constants
LIMIT is public static final: static because one value serves the whole class, and final because it can never be reassigned. Any assignment such as Ticket.LIMIT = 600; is a compile error, anywhere. Constants are written in capitals by convention and are often public, since nobody can change them.
Concept Check 🎯
Use the Ticket class above.
What a Static Method Can Reference
A static method is called on the class, not on an object, so inside it there is no current object and no this.
| Inside a static method of class Ticket | Allowed? |
|---|---|
static variables and static methods, by name (issued, getIssued()) | yes |
| its own parameters and local variables | yes |
an instance variable by its bare name (number) | no — whose number? |
an instance method by its bare name (getNumber()) | no — called on which object? |
the keyword this | no |
an instance variable or method through an object reference (t.number, t.getNumber()) | yes |
// inside Ticket
public static int later(Ticket t1, Ticket t2) {
if (t1.number > t2.number) { // OK: instance data through references
return t1.number;
}
return t2.number;
}
public static int lastNumber() {
return number; // does NOT compile: no current object
}
An instance method has no such limits: it can use instance variables, static variables, instance methods and static methods, because it always runs on some object and can also see everything the class shares.
🔑 Key Concept: Make a method static when its job does not depend on any one object's state, such as reporting a class-wide count or doing a calculation from its parameters alone. If it needs one object's fields, make it an instance method, or pass the object in as a parameter.
Static or Not? 🔍
Worked Example: A Shared Team Total
public class Player {
private static int playerCount = 0;
private static int teamPoints = 0;
private String name;
private int points;
public Player(String n) {
name = n;
points = 0;
playerCount++;
}
public void score(int p) {
points += p;
teamPoints += p;
}
public double share() {
return (double) points / teamPoints;
}
public static double average() {
return (double) teamPoints / playerCount;
}
}
Player a = new Player("Ana");
Player b = new Player("Bo");
a.score(6);
b.score(4);
a.score(10);
Step 1 — Separate the two kinds of state. playerCount and teamPoints have one copy each. name and points exist once per Player.
Step 2 — Trace.
| Statement | playerCount | teamPoints | a.points | b.points |
|---|---|---|---|---|
new Player("Ana") | 1 | 0 | 0 | |
new Player("Bo") | 2 | 0 | 0 | 0 |
a.score(6) | 2 | 6 | 6 | 0 |
b.score(4) | 2 | 10 | 6 | 4 |
a.score(10) | 2 | 20 | 16 | 4 |
Step 3 — Evaluate. a.share() is 16 / 20 = 0.8 and b.share() is 4 / 20 = 0.2. Player.average() is 20 / 2 = 10.0.
Step 4 — Check the method kinds. share must be an instance method because it reads one player's points. average uses only class variables, so it is static and is called as Player.average().
AP-Style Application 🎯
Use the Player trace above.
Part 3: Scope, Shadowing, and Access
🏛️ Class Design
Part 3 of 7 — Scope, Shadowing, and Access
Scope is the part of a program where a name can be used (CED Topic 3.8). Part 1 listed the four kinds of variables. This part works through the rules that decide whether code compiles, which variable a name refers to when two share it, and who is allowed to use a private member.
| In this part |
|---|
| Where each kind of variable can be used |
| Shadowing: when a local name hides an instance variable |
| The two classic constructor and method bugs |
| Access: inside the class vs client code |
Where a Name Can Be Used
| Kind of variable | Scope begins | Scope ends |
|---|---|---|
| instance or class variable | anywhere in the class | the end of the class |
| parameter | the start of the method or constructor body | the end of that body |
| local variable | its declaration | the closing brace of the block that contains it |
| for-loop header variable | the loop header | the end of the loop |
public int sumSquares(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
int sq = i * i;
total += sq;
}
return total; // total is still in scope here
}
| A statement placed... | Compiles? | Why |
|---|---|---|
return sq; after the loop | no | sq's block (the loop body) has ended |
System.out.println(i); after the loop | no | i exists only inside the loop |
int total = 5; inside the loop body | no | a local variable named total is still in scope |
int sq = 0; after the loop | yes | the earlier sq is out of scope, so the name is free |
private int count = 0; inside the method | no | access modifiers are not allowed on local variables |
Local variables, including parameters, exist only while their method runs. Each call gets fresh copies, which is why a value that must survive between calls has to be an instance variable.
Concept Check 🎯
public int countBig(int limit) {
int count = 0;
for (int k = 1; k <= 5; k++) {
int value = k * limit;
if (value > 10) {
int extra = value - 10;
count += extra;
}
}
return count;
}
Shadowing: The Local Name Wins
When a local variable or parameter has the same name as an instance variable, the bare name refers to the local one everywhere in its scope. The instance variable is still there, but it is hidden, or shadowed. Only this.name reaches it.
public class Counter {
private int count;
public Counter(int count) {
count = count; // Bug 1
}
public void reset() {
int count = 0; // Bug 2
}
public void add(int n) {
count += n; // no local named count: this is the field
}
public int getCount() {
return count;
}
}
Worked Example: Tracing the Two Bugs
Counter c = new Counter(5);
c.add(3);
c.reset();
System.out.println(c.getCount());
Step 1 — Constructor. Inside the constructor, count means the parameter. count = count; copies the parameter into itself, and the field keeps its default value of 0. It compiles, which is what makes the bug dangerous.
Step 2 — add(3). No local variable named count exists in add, so count is the field, which becomes 3.
Step 3 — reset(). int count = 0; declares a new local variable that happens to share the field's name. The local is set to 0 and vanishes when the method ends. The field is untouched.
Step 4 — Output. 3. The intended answer was 0, since a reset counter should read 0.
| Bug | Fix |
|---|---|
count = count; in a constructor | this.count = count; or rename the parameter (int start) |
int count = 0; in a method meant to change the field | remove the type: count = 0; |
🎯 AP Connection: Both bugs compile, so the exam tests them with "what is printed" questions. Whenever a name appears both as a field and as a parameter or local, ask which one is in scope at that line.
Which count? 🔍
Use the Counter class above.
Access: Who May Use a Private Member?
Scope answers "is this name visible here?" Access answers "is this code allowed to use it?" private means usable only by code written inside the same class.
| Member | Code inside the class | Client code in another class |
|---|---|---|
| private instance variable | yes, by name or through any reference of this class | no |
| private method (helper) | yes | no |
| public method or constructor | yes | yes |
| public static final constant | yes | yes, as ClassName.NAME |
public class Grade {
private int points;
private int possible;
public Grade(int pts, int poss) {
points = pts;
possible = poss;
}
public boolean passed() {
return percent() >= 60;
}
private double percent() {
return 100.0 * points / possible;
}
}
passed() calls the private helper percent(), which is fine because both are inside Grade. A client may call g.passed() but not g.percent(), and may not read g.points.
new Grade(14, 20).passed()returns true: the helper computes 100.0 * 14 / 20 = 70.0.- Writing
100.0 * pointsfirst matters:100 * points / possiblewould use int division, which happens to give 70 here but gives 66 instead of 66.66... for 2 out of 3.
AP-Style Application 🎯
Use the Grade class above. Each statement is written in a client class, with Grade g = new Grade(9, 12); already declared.
Part 4: The this Keyword
🏛️ Class Design
Part 4 of 7 — The this Keyword
Inside a constructor or an instance method, the keyword this is a reference to the current object: the object being constructed, or the object the method was called on (CED Topic 3.9). Part 1 used this.name = name to get around shadowing. This part shows what else this does.
| In this part |
|---|
this as a reference to the current object |
Implicit this in field names and method calls |
Passing this as an argument |
Returning this, and comparing with this |
What this Refers To
Box a = new Box(5);
Box b = new Box(3);
a.grow(2); // inside grow, this refers to the same object as a
b.grow(2); // inside grow, this refers to the same object as b
The same method body runs both times. this is how that body refers to whichever object it was called on.
Implicit this
When no local variable or parameter shadows a field, a bare field name already means this.field, and a bare instance-method call means this.method():
| You write (inside an instance method) | Java reads it as |
|---|---|
size += n; | this.size += n; |
if (fitsIn(other)) | if (this.fitsIn(other)) |
return size; | return this.size; |
So this. is required only when a local name shadows a field. Writing it elsewhere is legal and sometimes clearer.
Where this Cannot Appear
A static method has no current object, so this inside a static method is a compile error.
public class Box {
private int size;
public Box(int size) {
this.size = size;
}
public void grow(int n) {
size += n;
}
public boolean fitsIn(Box other) {
return size < other.size;
}
public Box larger(Box other) {
if (this.fitsIn(other)) {
return other;
}
return this;
}
public int getSize() {
return size;
}
}
larger returns this: a reference to the object it was called on, not a copy. a.larger(b) returns a reference to the same object as a whenever a does not fit in b.
Concept Check 🎯
Use the Box class above.
Passing this as an Argument
Sometimes an object must hand itself to another object, for example to register with it or to link back to it.
public class Student {
private String name;
private Student partner;
public Student(String name) {
this.name = name;
partner = null;
}
public void pairWith(Student other) {
partner = other;
other.partner = this;
}
public String partnerName() {
if (partner == null) {
return "none";
}
return partner.name;
}
}
Inside pairWith, this is the student the method was called on and other is the parameter. other.partner = this; makes the link two-way: the other student now refers back to the caller.
Worked Example: Re-pairing
Student a = new Student("Ana");
Student b = new Student("Ben");
Student c = new Student("Cal");
a.pairWith(b);
c.pairWith(a);
Step 1 — a.pairWith(b). this is a, other is b. a.partner becomes b, and b.partner becomes a.
Step 2 — c.pairWith(a). this is c, other is a. c.partner becomes a, and a.partner becomes c, replacing b.
Step 3 — Read the links.
| Student | partner refers to | partnerName() |
|---|---|---|
| a | c | "Cal" |
| b | a | "Ana" |
| c | a | "Ana" |
Step 4 — Notice the stale link. b still points at a, but a no longer points at b. The method does not "unpair" an old partner; a fuller version would first set the old partner's link to null.
🎯 AP Connection: In a trace, rename
thisand the parameter to the actual variables for each call ("this is c, other is a") before following any assignments. Most errors come from losing track of which object is which.
Applied Recall ✍️
-
Inside an instance method, the keyword that refers to the object the method was called on is _______.
-
Starting from three new Students a, b and c (with the class above), run
b.pairWith(c); a.pairWith(c);. What doesb.partnerName()return? (Type the name only.) _______ -
In the same scenario, what does
c.partnerName()return? _______
Comparing With this
Because this is a reference, this == other asks whether two variables refer to the same object, which is useful for guarding against an object being paired with, or transferring to, itself.
public void pairWith(Student other) {
if (other != this) {
partner = other;
other.partner = this;
}
}
With the guard, a.pairWith(a) changes nothing. Without it, a would become its own partner.
| Expression inside an instance method | Meaning |
|---|---|
this | the current object |
this.field | a field of the current object (needed when shadowed) |
this.method(x) | call another instance method on the current object |
obj.method(this) | hand the current object to another method |
return this; | give the caller a reference to the current object |
other == this | does the parameter refer to the current object? |
AP-Style Application 🎯
Part 5: Program Design: Abstraction, Decomposition, and Impact
🏛️ Class Design
Part 5 of 7 — Program Design: Abstraction, Decomposition, and Impact
Good class design is not only about syntax. The CED asks you to describe how abstraction makes large programs manageable and how a large task is broken into methods (Topic 3.1), and to explain the effects programs have beyond their code: reliability, legal and intellectual-property issues, and social impact (Topic 3.2).
| In this part |
|---|
| Data and procedural abstraction |
| Decomposing a task into private helper methods |
| Overloading: what makes two method headers different |
| Reliability, intellectual property, and impact |
Abstraction
Abstraction makes a program easier to understand by focusing on what something does and hiding the details of how it is done.
| Kind | What is hidden | Example |
|---|---|---|
| Data abstraction | how the data is stored | a Grade object's private fields; clients see only passed() |
| Procedural abstraction | how a method does its job | you call Math.sqrt(x) without knowing its algorithm |
A method's name, parameters and return type form its procedural abstraction: they say what it needs and what it gives back. As long as the header and its behavior stay the same, the body can be rewritten without breaking any caller.
Decomposition Into Helper Methods
A long method is easier to write, test and reuse when it is split into smaller methods, each doing one job. Helpers that clients do not need are private.
public class Course {
private int earned;
private int possible;
public Course(int e, int p) {
earned = e;
possible = p;
}
public String report() {
double pct = percent();
return pct + "% " + letterFor(pct);
}
private double percent() {
return 100.0 * earned / possible;
}
private String letterFor(double pct) {
if (pct >= 90) {
return "A";
} else if (pct >= 80) {
return "B";
} else if (pct >= 70) {
return "C";
}
return "F";
}
}
report reads almost like the specification: compute the percent, then attach a letter. new Course(87, 100).report() returns "87.0% B", and new Course(18, 20).report() returns "90.0% A".
Each helper can be tested on its own, and letterFor can be reused by any other method that needs a letter grade.
Concept Check 🎯
Use the Course class above.
Overloading: What Makes Two Headers Different
Part 1 defined overloading as methods with the same name and different parameter lists. The precise rule: a method's signature is its name plus the number, types and order of its parameters. Two methods in one class must have different signatures.
| Pair of headers in one class | Legal together? | Why |
|---|---|---|
int area(int s) and int area(int w, int h) | yes | different number of parameters |
double area(double r) and int area(int s) | yes | different parameter type |
void put(String k, int v) and void put(int v, String k) | yes | different order of types |
int area(int s) and double area(int s) | no | return type is not part of the signature |
int area(int s) and int area(int side) | no | parameter names are not part of the signature |
When a call is made, Java chooses the version whose parameter list matches the arguments. With both area(int s) and area(double r) present, area(5) runs the int version and area(5.0) runs the double version.
Legal Overload? 🔍
The Impact of Program Design
System Reliability
A program is reliable when it performs its tasks as expected under the stated conditions without failing. No amount of care guarantees perfection, so programmers raise reliability by testing with a variety of inputs, especially:
| Kind of test input | Example for letterFor(double pct) |
|---|---|
| typical values | 75.0, 85.0 |
| boundary values, on and next to each cutoff | 90.0, 89.9, 80.0, 70.0, 69.9 |
| extreme or unusual values | 0.0, 100.0, and what happens if possible is 0 |
The last row exposes a real gap in Course: new Course(0, 0).report() asks for a percent of a total of 0, which has no sensible value. The specification should say what to do in that case (for example, a precondition that possible is positive, or a rule to report 0%), and the code should follow it.
Intellectual Property and Licensing
Code is the intellectual property of its creator. Programmers often reuse code that others have published as open source, which is free to use under the terms of its license (for example, a requirement to credit the author). Using code that is not openly licensed requires the owner's permission, and often a purchase, before it can be included in a program.
Social, Economic and Cultural Impact
Programs affect society, economies and culture, and the effects can be beneficial or harmful. A program written to solve one problem can have unintended harmful effects beyond its intended use: an automated scheduling tool can save hours of work, but if it was built from biased data it can treat some groups of people unfairly.
🎯 AP Connection: Expect multiple-choice questions that describe a scenario and ask which action improves reliability (more varied tests, boundary tests), which use of code is legal (following an open-source license, getting permission), or which effect was unintended.
AP-Style Application 🎯
Part 6: AP-Style Practice
🏛️ Class Design
Part 6 of 7 — AP-Style Practice
Free-response question 2 (Class Design) can include a class variable, private helper methods, and constructor parameters that share a name with fields. Multiple-choice questions test static state, scope and this with short traces. This part practices both with the ideas of Parts 1–5.
How to Attack a Class-Design Question
| Step | Do this |
|---|---|
| 1 | Mark every variable as static (one copy) or instance (one per object) before tracing. |
| 2 | At each line, decide which variable a name refers to: a local or parameter wins over a field of the same name. |
| 3 | For each method call, write down what this and each parameter refer to. |
| 4 | For a static method, check that it uses no instance field by its bare name and never uses this. |
| 5 | Split a long method into private helpers that each do one job. |
🔑 Key Concept: A static counter that assigns IDs must be read into an instance variable before it is advanced, and it must be static, or every object gets the same number.
Practice Set 1: Tracing 🎯
public class Lamp {
private static int onCount = 0;
private boolean on;
public void toggle() {
on = !on;
if (on) {
onCount++;
} else {
onCount--;
}
}
public static int getOnCount() {
return onCount;
}
}
FRQ-Style Task — Locker
Prompt. Write the complete Locker class.
- Lockers are numbered in the order they are created, starting at 1.
getId()returns a locker's number, and the static methodgetLockersMade()returns how many Lockers have been created. - The constructor takes the locker's combination code (an int).
open(int attempt)returns true and clears the count of consecutive wrong attempts if attempt matches the code and the locker is not locked out. Otherwise it returns false; a wrong attempt adds 1 to the count of consecutive wrong attempts.- A locker is locked out once it has 3 consecutive wrong attempts. While locked out,
openreturns false even for the correct code. reset()clears the count of wrong attempts.
| Statement | Returns |
|---|---|
Locker a = new Locker(1234); | |
Locker b = new Locker(4321); | |
b.getId() | 2 |
a.open(1111) | false (1 wrong) |
a.open(1234) | true (count cleared) |
a.open(1) then a.open(2) then a.open(3) | false, false, false (locked out) |
a.open(1234) | false (locked out) |
a.reset(); then a.open(1234) | true |
Locker.getLockersMade() | 2 |
Solution
public class Locker {
private static int made = 0;
private int id;
private int code;
private int wrong;
public Locker(int code) {
made++;
id = made;
this.code = code;
wrong = 0;
}
public boolean open(int attempt) {
if (isLockedOut()) {
return false;
}
if (attempt == code) {
wrong = 0;
return true;
}
wrong++;
return false;
}
public void reset() {
wrong = 0;
}
public int getId() {
return id;
}
public static int getLockersMade() {
return made;
}
private boolean isLockedOut() {
return wrong >= 3;
}
}
- made is static: one count for the whole class. id, code and wrong are instance variables, one per locker.
- The constructor's parameter is named
code, the same as the field, sothis.code = code;is required. - The private helper
isLockedOutnames the rule from the specification, andopenchecks it first.
What a Rubric Looks For
| Point | Earned by |
|---|---|
| Fields | private instance fields for id, code and wrong count; a static creation count |
| Constructor | updates the static count and assigns this locker's id from it; stores the code in the field |
| open | refuses while locked out; clears the count on success; adds 1 on a wrong attempt; correct boolean on every path |
| reset / getId | change or return the right instance field |
| getLockersMade | static, returns the shared count |
Practice Set 2: Reasoning About Locker 🎯
Common Deductions on Static, Scope and this
| Mistake | Why it costs points |
|---|---|
| an ID counter declared as an instance variable | every object gets the same ID |
| the counter advanced after a failed condition or in a getter | the count no longer matches the objects created |
| a static method that names an instance field | does not compile |
this inside a static method | does not compile |
a constructor parameter that shadows a field, with no this. | the field keeps its default value |
| a field that must persist redeclared as a local in a method | the change is lost when the method ends |
| a helper method that should be private declared public | exposes implementation details |
🎯 AP Connection: Read the table of example calls for clues about what is shared. A value that counts or numbers all objects of the class must be static; a value that differs from object to object must be an instance variable.
Part 7: Synthesis Review
🏛️ Class Design
Part 7 of 7 — Synthesis Review
This part ties the topic together: class variables and methods (CED Topic 3.7), scope and access (3.8), the this keyword (3.9), and program design and its impact (3.1–3.2). Use the tables as a checklist, then test yourself on mixed questions.
The Topic on One Page
| Idea | Key fact | Typical trap |
|---|---|---|
| Class variables (Part 2) | one shared copy; initializer runs once | expecting each object to get its own copy |
| Unique IDs (Part 2) | copy the static counter into an instance field, then advance it | an instance counter gives every object the same ID |
| Constants (Part 2) | static final, cannot be reassigned | assigning to a constant from client code |
| Static methods (Part 2) | no current object, no this; instance data only through a reference | naming an instance field by its bare name |
| Scope (Part 3) | a local lives from its declaration to the end of its block | using a loop or block variable after its block |
| Shadowing (Part 3) | the local or parameter wins over a field of the same name | count = count; and int count = 0; |
| Access (Part 3) | private means usable only inside the class | client code calling a private helper |
| this (Part 4) | the current object; implicit in bare field names | this in a static method |
| Passing / returning this (Part 4) | hands over a reference to the current object, not a copy | losing track of which object is "this" |
| Design (Part 5) | abstraction, private helpers, signatures | thinking a new return type makes a new overload |
| Impact (Part 5) | reliability through varied tests; licenses; unintended effects | testing only typical values |
Worked Example: Putting It Together
public class Club {
private static int members = 0;
private String name;
private int dues;
public Club(String name, int dues) {
this.name = name;
dues = dues;
members++;
}
public void pay(int amount) {
int dues = this.dues - amount;
this.dues = dues;
}
public void merge(Club other) {
dues += other.dues;
other.dues = 0;
members--;
}
public static int getMembers() {
return members;
}
public String getInfo() {
return name + " " + dues;
}
}
Club x = new Club("Art", 50);
Club y = new Club("Band", 30);
x.pay(20);
x.merge(y);
System.out.println(x.getInfo() + " | " + y.getInfo() + " | " + Club.getMembers());
Step 1 — Constructors. this.name = name; stores the name. dues = dues; assigns the parameter to itself, so the field dues stays 0 for both clubs. members becomes 2.
Step 2 — x.pay(20). The local dues is this.dues - amount = 0 - 20 = -20, and this.dues = dues; stores -20 in x's field. This method uses the shadowing correctly: this.dues is the field and the bare dues is the local.
Step 3 — x.merge(y). this is x and other is y. x's dues become -20 + 0 = -20, y's dues are set to 0, and the shared members count drops to 1.
| After | x.dues | y.dues | members |
|---|---|---|---|
| constructors | 0 | 0 | 2 |
x.pay(20) | -20 | 0 | 2 |
x.merge(y) | -20 | 0 | 1 |
Step 4 — Output. Art -20 | Band 0 | 1. With the constructor fixed to this.dues = dues;, the output would be Art 60 | Band 0 | 1.
Mixed Review 1 🎯
Use the Club class above, with the constructor bug still present.
Class-Design Checklist
| Check | Question to ask |
|---|---|
| Static or instance? | Does this value describe one object, or the whole class? |
| IDs | Is the counter static, and is it copied into an instance field each time? |
| Static methods | Do they avoid bare instance-field names and this? |
| Constructor parameters | Do any share a name with a field? If so, is this. used? |
| Locals | Does any method redeclare a field's name with a type in front? |
| Scope | Is every variable used only inside the block that declares it? |
| Access | Are fields and helper methods private, and the interface public? |
| Signatures | Do overloaded methods differ in their parameter types, not just their return types? |
| Testing | Have boundary and unusual inputs been tried? |
Error Catalogue
| Symptom | Likely cause | Fix |
|---|---|---|
| every object has the same ID | counter is an instance variable | declare it static |
| a field keeps 0 or null after construction | parameter shadows it without this. | use this.field = param; |
| a reset or update has no effect | int x = ... declared a local with the field's name | drop the type |
| "non-static variable cannot be referenced from a static context" | a static method names an instance field | make the method an instance method, or use an object reference |
| "cannot find symbol" after a loop | a loop or block variable used outside its block | declare it before the block |
| "method is already defined" | two methods differ only in return type or parameter names | change the parameter types or the name |
Quick Evaluation 🔍
Mixed Review 2 🎯