Unit 03
Class Creation
Stop using other people's classes and write your own, deciding what an object knows, what it can do, and what it refuses to let anyone touch.
Every check for understanding filed under this unit, and where each one stands with your classes. The whole console →
- What the constructor is for checking
- name = name checking
- Knows and does checking
- Whose code, and does it hold up? checking
- What the method actually got checking
- One copy, or one each checking
Every class you have used so far arrived finished. String knows how to find a
substring, Math knows how to round, and you have been calling their methods
without ever asking who decided what those methods should be. This unit is
where you start deciding.
It is the smallest unit on the exam and the one that changes most about how you write. The free-response question on class design comes from here, and so does every project after it — because from now on the answer to “where should this go?” is a class you wrote.
3.1 · Abstraction and program design
Abstraction is reducing complexity by hiding what does not matter right
now. You have been doing it since Unit 1 — Math.sqrt(x) is a name in front of
an algorithm you have never read and do not need to.
Designing a class starts on paper, with two lists.
- What does it know? Those become attributes — variables declared in the class body, outside every method. An attribute whose value belongs to one object is an instance variable.
- What can it do? Those become methods.
That is the whole distinction the rest of the unit rests on. A class is a description; an object is a thing made from the description. The description is never one of the things.
The drawing is the class. The house is an object built from it. You could build a second house from the same sheet, and it would weather differently — its own paint, its own vines, its own state — while the drawing stayed exactly as drawn.
The other half of 3.1 is procedural abstraction: a method is a name for a process, and callers use it knowing only what it does. That is what buys you the freedom to rewrite the inside later. Every caller was written against the header, so the body is yours to change.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
You are designing a <code>LibraryBook</code> class on paper, before writing any Java. Which of these is an <em>attribute</em>?
The design question is always the same two lists: what does it know and what can it do. What it knows becomes attributes — instance variables declared in the class body, outside any method. What it can do becomes methods. Writing the two lists before you open an editor is the whole of 3.1, and it is what the class-design free-response question is really testing.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
A class has <code>public double average()</code>. You rewrite its body to be twice as fast, keeping the same header and the same answers. How much of the code that calls it has to change?
This is procedural abstraction: a name for a process, usable knowing only what it does and not how. Because callers were written against average() and not against its insides, you are free to make the insides faster, smaller, or clearer at any time. That freedom is the return on the work of designing a good method header — and you lose it the moment a caller starts depending on something the header never promised.
3.2 · Impact of program design
This topic and 4.1 are the only two in the course that ask you to explain consequences rather than code. They are on the exam. They are also the reason any of this matters.
Reliability is a program doing what it is supposed to do, under the conditions it will actually meet, without failing. The trap is that the conditions you test with are the ones you thought of.
Notice what kind of failure that was. Not a typo, not a bad algorithm — two pieces of correct code with an unstated assumption between them. That is a design failure, and it is the failure this unit is built to prevent: a class that states what it holds and what it promises leaves fewer assumptions unwritten.
Software also has impacts, beneficial and harmful, and usually both at once. A tool that grades faster gives a teacher back an hour and decides something about a student without being asked to explain itself. You are not required to solve that. You are required to notice it before you ship.
art wanted Then there is intellectual property. Programmers reuse published code constantly, and that works because a licence says in advance what you may do. Read it, follow it, and name the author. In this class that means a comment naming your source. On this site it means every borrowed image above carries its photographer and its licence, including the ones that were free.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
A grade calculator works perfectly on every class you tested it with, then crashes on the first day of term for a teacher whose roster is still empty. What does this say about the program?
System reliability is a program doing what it is supposed to do, under the stated conditions, without failing. The stated conditions include the boring ones — an empty list, a zero, a name with an apostrophe in it — and those are the ones that never appear in the data you happened to test with. Every division you write is a question about what happens when the divisor is zero, and someone will eventually supply it.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
You find a sorting method on a public GitHub repository that does exactly what your project needs. What does using it require?
Programmers reuse published code constantly, and the whole system works because a licence says in advance what you may do with it. Read it before you paste. Then say where it came from — in this course that is a comment naming the source, and on any assignment it is the difference between reuse and plagiarism. Every borrowed thing on this site carries its author and its licence for the same reason.
3.3 · Anatomy of a class
Here is the shape every class you write this year will have.
public class Player {
private String name; // attributes — what it knows
private int health;
public Player(String n) { // constructor — how it starts
name = n;
health = 100;
}
public int getHealth() { // behaviours — what it can do
return health;
}
}
Encapsulation is keeping the implementation of a class hidden from
everything outside it. Two keywords do the work. public means reachable from
anywhere; private means reachable only from inside this class.
The convention is not arbitrary:
- Attributes are
private. They are the implementation. Expose them and every outside caller becomes something you have to keep working. - Methods are
publicorprivateon purpose. Public if the class is offering it; private if it is a helper that only makes sense inside.
In this course, classes are always public, and so are constructors. The
interesting decisions are all about the members.
And every object gets its own copy of every instance variable — that is what makes objects worth having. One class, a thousand players, a thousand separate healths.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Which of these belongs to the <em>object</em> rather than to a single method call?
public class Player {
private int health; // A
public void takeHit(int amount) {
int remaining = health - amount; // B
health = remaining;
}
} health is declared in the class body, so every Player object gets its own and it lasts as long as the object does. remaining is declared inside a method, so it is created on entry and gone on return. Where you declare it decides how long it lives.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
Counter a = new Counter();
Counter b = new Counter();
a.bump();
a.bump();
b.bump();
System.out.println(a.value() + " " + b.value()); An instance variable belongs to the object, so new hands out a fresh one every time. a and b each carry their own count, and bumping one cannot be seen from the other. This is the single most useful fact about objects: they let you have many of something without writing many of anything. Topic 3.7 shows what changes when you deliberately give up that independence.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Which combination of access modifiers is the good-practice default for a class you are designing?
Encapsulation is keeping the implementation of a class hidden from the code outside it. Attributes are the implementation, so they are private by default. Behaviours are the offer, so each method is public or private on purpose: public if it is part of what the class does for others, private if it is a helper that only makes sense inside. A private helper is not a lesser method — it is a method you have reserved the right to change.
3.4 · Constructors
An object’s state is its attributes and their values right now. A constructor exists to set the initial state, and it should set all of it — every instance variable given a value before anybody else can look.
public Player(String n) {
name = n;
health = 100;
}
Three rules that catch people out.
Write no constructor and Java writes one for you — a no-argument one that
leaves every field at its default. int starts at 0, double at 0.0,
boolean at false, and every reference type at null.
Write any constructor and the free one disappears. The moment Player(String)
exists, new Player() stops compiling. If you want both, write both.
A mutable object handed to a constructor is still the caller’s object.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
public class Dog {
private String name;
public Dog(String n) {
name = n;
}
public String getName() {
return name;
}
}
// elsewhere
Dog d = new Dog("Rex");
System.out.println(d.getName()); A constructor exists to set an object’s initial state. new Dog("Rex") passes "Rex" in as n, and the body assigns it to the instance variable name, which then outlives the constructor call. Leave that assignment out and name stays null.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
<code>new Dog()</code> used to work and now it does not. What changed?
public class Dog {
private String name;
public Dog(String n) { name = n; }
}
Dog d = new Dog(); // will not compile Java gives you a no-argument constructor only as a courtesy, and only while you have not written one yourself. The moment you write Dog(String), the courtesy is withdrawn — if you still want new Dog(), you have to write it.
That third rule is the one that bites hardest, because the code looks finished:
public Order(Address a) {
ship = a; // the caller still holds it
}
public Order(Address a) {
ship = new Address(a.getCity()); // now it is yours
}
The second version makes a defensive copy. Without it, whoever passed the
Address in can keep changing it afterwards, and your order will quietly change
with it. Whenever a constructor takes a mutable object, ask who else is still
holding a reference to it.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does the last line print?
public class Order {
private Address ship;
public Order(Address a) {
ship = a;
}
public String city() { return ship.getCity(); }
}
Address home = new Address("Athens");
Order o = new Order(home);
home.setCity("Atlanta");
System.out.println(o.city()); The constructor stored the caller’s reference, so home and ship are two names for one Address. Anyone holding the original can now reach inside the order and change where it ships, without the order getting any say. The fix is a defensive copy — ship = new Address(a.getCity()); — so the order owns an Address nobody else has a reference to. Whenever a constructor takes a mutable object, ask who else is still holding it.
3.5 · Methods, and how to write them
A method’s header is a promise about what comes back. void promises nothing
comes back; any other return type promises exactly one value of that type.
return also ends the method immediately. Anything after it in the same block
is unreachable, and the compiler will say so.
Two shapes cover almost everything you will write:
| Accessor | Mutator | |
|---|---|---|
| Job | Report what the object knows | Change what the object knows |
| Return type | The type of the thing it reports | Usually void |
| Parameters | Usually none | The new value |
| Named | getHealth() | setHealth(int h) |
The naming is convention, not syntax — but it is a convention every Java reader depends on, including whoever scores the free-response question.
Finally, a primitive argument is copied in. The parameter is a fresh variable initialised with the value, and changing it inside the method has no effect outside. Hold on to that sentence, because 3.6 is about what happens when the argument is not a primitive.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
A method is declared <code>public void setSpeed(int s)</code>. Which is it, and how can you tell from the header alone?
An accessor gives back a copy of what the object knows: non-void, usually no parameters, conventionally named getSomething. A mutator changes what the object knows: usually void, usually takes the new value, conventionally setSomething. The naming is a convention rather than a rule, but it is a convention every Java reader relies on — including whoever grades the free-response question.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Why is this rejected?
public void addPoints(int n) {
score += n;
return score;
} The return type is a promise: void promises nothing comes back, so handing something back breaks the contract. Decide what the method is for — if the caller needs the new score, declare it int; if it just needs the update to happen, drop the return.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
public static void bump(int n) {
n = n + 10;
}
int score = 5;
bump(score);
System.out.println(score); When an argument is a primitive, the parameter is initialised with a copy of the value, and changes to the parameter have no effect on the variable that was passed in. If bump is supposed to be useful, it has to return the new value and the caller has to store it: score = bump(score);. Hold this result next to the one in 3.6, where the argument is an object — the rule is identical, and the outcome is not.
3.6 · Passing and returning references
This is the hardest topic in the unit and the one most likely to appear on the exam in a form you did not expect.
The rule does not change: Java always copies the argument. What changes is what there is to copy. For a primitive, the value gets copied. For an object, the reference gets copied — the arrow, not the thing it points at.
So a method holding your object can do two very different things, and only one of them is visible to you.
References
Predict first
What does the last line print?
public static void tag(Dog a) {
a.setName("Buddy");
a = new Dog("Ghost");
a.setName("Spectre");
}
Dog pet = new Dog("Rex");
tag(pet);
System.out.println(pet.getName());
Variables
Objects
Dog
- name
- ·
nothing points here
Dog
- name
- ·
nothing points here
Watch which arrow moves at each step. That is the whole topic.
Line 2 changed the Dog that pet can see, because there was only one Dog and two arrows pointing at it. Line 3 re-aimed the method's own arrow, which the caller never sees. Line 4 then did careful work on an object nothing outside the method could reach. The rule is unchanged from 3.5 — the argument is copied — but what got copied was the arrow.
Follow it through once more without the picture: you can change the object
through the reference you were given, and the caller sees it. You cannot
re-point the caller’s variable, because you were given a copy of the arrow.
This is exactly why Java cannot write you a swap method, and why that is not a
gap in your understanding.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
public static void rename(Dog d) {
d.setName("Fido");
}
Dog pet = new Dog("Rex");
rename(pet);
System.out.println(pet.getName()); Java always copies the argument — but for a reference type, what gets copied is the arrow, not the object. Both pet and d point at one Dog, so a change through either is visible through both. Reassigning d itself inside the method, however, would change nothing outside it.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What does this print?
public static void swap(Dog a, Dog b) {
Dog temp = a;
a = b;
b = temp;
}
Dog x = new Dog("Rex");
Dog y = new Dog("Fido");
swap(x, y);
System.out.println(x.getName()); The parameter is initialised with a copy of the reference, so a and x are two arrows pointing at one Dog. swap re-aims its own two arrows and returns; x and y are untouched. Compare this with rename above: changing the object through the arrow is visible outside, changing which object the arrow points at is not. Java genuinely cannot write a swap method for you, and that is not a gap in your understanding.
The same rule runs backwards. When a method returns an object, the reference
is returned, not a copy — so an innocent-looking accessor can hand out the
very object your private field was protecting.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
The field is private and there is no setter. What does this print?
public class Team {
private Coach coach = new Coach("Reyes");
public Coach getCoach() { return coach; }
}
Team t = new Team();
t.getCoach().setName("Okafor");
System.out.println(t.getCoach().getName()); When a return expression evaluates to an object reference, the reference is returned — not a reference to a new copy. So getCoach() hands the caller the very Coach the team is holding, and private turns out to have protected nothing. Either return a copy, or return only the piece the caller actually needs (getCoachName()). This is the mirror image of the constructor problem in 3.4: one leaks on the way in, this one leaks on the way out.
One more thing about privacy, because it surprises everyone: a method can reach
into the private data of a parameter when that parameter is the same type as
the class the method is in. private draws its wall around the class, not
around each object. Without that rule, no class could ever compare two of its
own instances.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
<code>x</code> is private, and <code>other</code> is somebody else’s object. Why does <code>other.x</code> compile here?
public class Point {
private int x;
public boolean leftOf(Point other) {
return this.x < other.x;
}
} A method may reach the private data of a parameter when that parameter is the same type as the method’s own class. It is the rule that makes comparison methods possible at all — without it, no Point could ever be compared to another Point without first exposing its coordinates to everyone. Note the limit: make other a Circle instead and other.x stops compiling immediately.
3.7 · Class variables and methods
static means belongs to the class, not to any object. One copy, shared by
everything.
You met this idea back at 1.12. Here is the same machine again, because static-versus-instance is what this topic is actually about — press new a few times, paint one robot, then empty the yard and watch what the counter does.
One blueprint, many objects
Press new and watch what changes and what doesn't. The drawing on the left is the class. Every robot on the right is an instance of that class.
class Robot
static Robot.totalCount = 0
One counter for the whole class. Not one per robot.
Nothing built yet. The blueprint is not an object — you cannot paint it, and you cannot point at it and say "that one".
Colour is instance state: painting one robot paints one robot. The count is class state: there is exactly one of it, every constructor call touches the same one, and emptying the yard does not reset it, because the number of robots ever built is a fact about the class rather than about any robot.
Two consequences follow, and both are exam material:
- A class method has no object, so it cannot touch instance variables or
call instance methods. It can use class variables freely. This is why
mainisstaticand why it usually does nothing but make an object. - A variable declared
finalcannot be reassigned after it is set.static finalis how constants are written.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
A class declares <code>private static int count;</code> and the constructor does <code>count++</code>. After three objects are created, what is count?
static means the variable belongs to the class, not to any object. There is one count in memory, every constructor call increments the same one, and asking any object gives you the same answer. This is the standard way to count instances.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
One of these two methods will not compile. Which, and why?
public class Robot {
private String name;
private static int count;
public static void report() {
System.out.println(name + " reporting");
}
public static int howMany() {
return count;
}
} A class method is called on the class — Robot.howMany() — so it runs without any particular robot in hand. count belongs to the class, so it is reachable. name belongs to an object, and there is no object, so the compiler rejects it rather than guessing. If a static method needs an instance, it has to be handed one as a parameter. This is also why main is static and why it usually does almost nothing except make an object.
3.8 · Scope and access
Two different questions get confused constantly, so name them separately.
Scope is where a name exists. A local variable — declared in a method body, a block, or a method header — exists from its declaration to the closing brace of its block, and nowhere else.
Access is who is allowed to reach it. That is public and private.
| Inside the class | Outside the class | |
|---|---|---|
public method | Yes | Yes |
private method | Yes | No |
public attribute | Yes | Yes — which is why you should not |
private attribute | Yes, on any object of this class | No |
There is a third thing that looks like both and is neither. When a local variable or parameter has the same name as an instance variable, the nearer one wins inside that block. The field is not gone; it is shadowed. That is what breaks the constructor in 3.9.
Find the error · java
One line is wrong
Which line does the compiler reject?
Both big declarations die at their own closing brace, so by line 7 there is no such name. Declare it once before the if and assign inside each branch. Java is being pedantic about something worth being pedantic about: a variable that outlived its block would be a variable nobody could reason about.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Why does the last line fail?
public class Account {
private double balance;
public double getBalance() { return balance; }
}
Account a = new Account();
System.out.println(a.balance); private is a wall with a door in it. The wall stops outside code from reaching balance directly; getBalance() is the door. That indirection is what lets you later add a rule — logging, validation, a currency conversion — without every caller having to change.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
Why does the <code>return</code> line fail to compile?
public int larger(int a, int b) {
if (a > b) {
int big = a;
} else {
int big = b;
}
return big;
} A local variable lives from its declaration to the closing brace of the block that holds it, and not one line further. Both big declarations die at their own }, so by the return there is no such name. Move the declaration out and the assignments stay in: int big; if (a > b) { big = a; } else { big = b; } return big;. The habit worth building is to declare a variable in the smallest block that can hold it — and then notice when that block is too small.
3.9 · The this keyword
Inside an instance method or a constructor, this is a reference to the
object whose method is running right now. Call rex.speak() and this is
Rex; call fido.speak() and the same code has this meaning Fido.
It does two jobs.
It un-shadows a field. This is the single most common bug in first-year class code, and it fails silently:
Find the error · java
One line is wrong
This compiles and the name is never set. Which line is the problem?
The parameter shadows the field, so both sides of name = name are the parameter — the line assigns it to itself and the field stays null. this.name = name; says the field on this object, specifically. Some compilers warn about a self-assignment and some do not, so do not rely on being told.
It passes the current object. arena.register(this) means “register me” —
and since it is a reference, everything 3.6 said about handing out references
applies to it too.
Class methods have no this, for the reason 3.7 gave: there is no object for it
to mean.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
The name never gets set. Why?
public class Dog {
private String name;
public Dog(String name) {
name = name;
}
} When a parameter and a field share a name, the nearer one wins, so both sides of name = name refer to the parameter. this.name says "the field on this object, specifically". Some compilers warn about a self-assignment; do not count on it.
Quick check · not graded, try as many times as you like
Add this question to
Loading your meetings…
What is handed to <code>register</code> here?
public class Monster {
private String name;
public void enter(Arena arena) {
arena.register(this);
}
} this is a reference to the object whose method is currently running, so arena.register(this) means "register me". Call godzilla.enter(a) and the arena registers Godzilla; call it on another monster and it registers that one instead. It is the same this as in this.name — one used to reach a field, one passed whole. And it is a reference, so the arena now holds an arrow to your monster: everything 3.6 says about handing out references applies.
The projects · Monster, then MonsterBattle
Two projects, in this order, and the order is the point. You write a class from nothing. Then you read a working one and see what you would do differently.
Project 1 · Monster
Write a Monster class. There is no starter. That is deliberate: this is the
class-design free-response question in disguise, and the FRQ does not come with
a starter either.
| Required | Why it is required |
|---|---|
At least four private attributes, including one String and one number |
Encapsulation is the default, not a flourish (3.3) |
| A constructor that gives every attribute a value | An object should never be born half-set (3.4) |
| A second, overloaded constructor | Two reasonable ways to make one (3.4) |
| An accessor for anything the outside genuinely needs | Not one per field — decide (3.5) |
| At least one mutator that changes state | void, takes the new value (3.5) |
One use of this to un-shadow a parameter |
The bug in 3.9, avoided on purpose |
A static count of how many monsters exist |
Class state, not instance state (3.7) |
Test it with a main that makes three monsters, prints them, damages one and
prints them again. If damaging one changes the others, an attribute that should
have been instance state is static.
Where it goes wrong
name = namein the constructor. Silent. Everything is null afterwards.- A getter for every field, reflexively. Ask what the outside actually needs. A field nobody reads does not need a door.
- Attributes left
public“for now”. For now lasts until the project is graded. staticon something that is not shared. One health bar for every monster in the game is a memorable bug.
| How it is graded | Weight |
|---|---|
| All attributes private; constructors set every one of them | 30% |
| Both constructors work, and the overload is a real second way to build one | 20% |
| Accessors and mutators chosen deliberately, named by convention | 20% |
this and static each used correctly and for a reason |
20% |
| Readable: real names, no dead code, comments only where it is not obvious | 10% |
Project 2 · MonsterBattle
Now the game. The starter is
dadiletta/MonsterBattle: a working
GUI, a demo game to read, and a Game.java full of TODOs that is yours.
Read GameDemo.java first, then run it. It is a complete working game, and
it is the fastest way to see what the GUI can do.
Then open the starter’s Monster.java and put it beside yours. It is about
thirty lines and it contains this whole unit — private fields, a no-argument
constructor, an overloaded one, accessors, a mutator. The overloaded constructor
does something yours probably did not:
public Monster(String special) {
this(); // run the other constructor first
this.special = special;
}
this() calls another constructor in the same class. It means the random
health, damage and speed are set in exactly one place instead of two. If you
duplicated that code between your two constructors, this is the fix — and
noticing that yourself is worth more than being told.
The milestones
- Make it yours. Change the title, the starting health, the number of monsters. Run it after every change.
- Make the four buttons do something. Attack, defend, heal, item. Each one
is a method on
Game, and each one changes state and then tells the GUI. - Add an item with a real effect. Copy the shape from
GameDemo, change what happens inside. - Win and lose properly. The loop has to end both ways, and say which.
- Use your own
Monster. Drop in the class you wrote in Project 1 and make the game work with it. This is the milestone that proves the first project was not busywork.
| How it is graded | Weight |
|---|---|
| Four actions implemented, each changing state and updating the display | 30% |
| The game ends correctly on both a win and a loss | 20% |
| At least one item with an effect you wrote | 15% |
| Your own Monster class, in use | 25% |
| Readable: methods that do one thing, named for what they do | 10% |
If you finish early: give a monster a special move that only fires below
half health. That is one if inside one method — and the fact that it is that
small, in a game this size, is what a well-designed class buys you.
Where this goes next
You can design an object now. Unit 4 gives you somewhere to put a thousand of
them, and the reason ArrayList<Monster> looked strange in Game.java is that
it is the last piece: collections, and the algorithms that go through them.
The framework, in full
Every topic College Board lists for this unit, with the learning objectives and essential knowledge in their words rather than mine. If something below isn't covered above yet, that gap is real. Open it, read the objective, then come find me.
-
3.1 Abstraction and Program Design 1 objective
3.1.A Represent the design of a program by using natural language or creating diagrams that indicate the classes in the program and the data and procedural abstractions found in each class by including all attributes and behaviors.
- 3.1.A.1Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
- 3.1.A.2Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. Data abstraction manages complexity by giving data a name without referencing the specific details of the representation. Data can take the form of a single variable or a collection of data, such as in a class or a set of data.
- 3.1.A.3An attribute is a type of data abstraction that is defined in a class outside any method or constructor. An instance variable is an attribute whose value is unique to each instance of the class. A class variable is an attribute shared by all instances of the class.
- 3.1.A.4Procedural abstraction provides a name for a process and allows a method to be used only knowing what it does, not how it does it. Through method decomposition, a programmer breaks down larger behaviors of the class into smaller behaviors by creating methods to represent each individual smaller behavior. A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for code reuse, which helps manage complexity.
- 3.1.A.5Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
- 3.1.A.6Using procedural abstraction in a program allows programmers to change the internals of a method (to make it faster, more efficient, use less storage, etc.) without needing to notify method users of the change as long as the method signature and what the method does is preserved.
- 3.1.A.7Prior to implementing a class, it is helpful to take time to design each class including its attributes and behaviors. This design can be represented using natural language or diagrams.
-
3.2 Impact of Program Design 1 objective
3.2.A Explain the social and ethical implications of computing systems.
- 3.2.A.1System reliability refers to the program being able to perform its tasks as expected under stated conditions without failure. Programmers should make an effort to maximize system reliability by testing the program with a variety of conditions.
- 3.2.A.2The creation of programs has impacts on society, the economy, and culture. These impacts can be both beneficial and harmful. Programs meant to fill a need or solve a problem can have unintended harmful effects beyond their intended use.
- 3.2.A.3Legal issues and intellectual property concerns arise when creating programs. Programmers often reuse code written by others and published as open source and free to use. Incorporation of code that is not published as open source requires the programmer to obtain permission and often purchase the code before integrating it into their program.
-
3.3 Anatomy of a Class 1 objective
3.3.A Develop code to designate access and visibility constraints to classes, data, constructors, and methods.
- 3.3.A.1Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
- 3.3.A.2In this course, classes are always designated public and are declared with the keyword class.
- 3.3.A.3In this course, constructors are always designated public.
- 3.3.A.4Instance variables belong to the object, and each object has its own copy of the variable.
- 3.3.A.5Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise.
- 3.3.A.6Access to behaviors can be internal or external to the class. Methods designated as public can be accessed internally or externally to a class, whereas methods designated as private can only be accessed internally to the class.
-
3.4 Constructors 1 objective
3.4.A Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.
- 3.4.A.1An object’s state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a has-a relationship between the object and its instance variables.
- 3.4.A.2A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.
- 3.4.A.3When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable does not hold a reference to the original object, and methods are prevented from modifying the state of the original object.
- 3.4.A.4When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default constructor.
- 3.4.A.5The default value for an attribute of type int is 0. The default value of an attribute of type double is 0.0. The default value of an attribute of type boolean is false. The default value of a reference type is null.
-
3.5 Methods: How to Write Them 1 objective
3.5.A Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.
- 3.5.A.1A void method does not return a value. Its header contains the keyword void before the method name.
- 3.5.A.2A non-void method returns a single value. Its header includes the return type in place of the keyword void.
- 3.5.A.3In non-void methods, a return expression compatible with the return type is evaluated, and the value is returned. This is referred to as return by value.
- 3.5.A.4The return keyword is used to return the flow of control to the point where the method or constructor was called. Any code that is sequentially after a return statement will never be executed. Executing a return statement inside a selection or iteration statement will halt the statement and exit the method or constructor.
- 3.5.A.5An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method.
- 3.5.A.6A mutator (modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method.
- 3.5.A.7Methods with parameters receive values through those parameters and use those values in accomplishing the method’s task.
- 3.5.A.8When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.
-
3.6 Methods: Passing and Returning References of an Object 1 objective
3.6.A Develop code to define behaviors of an object through methods written in a class using object references and determine the result of calling these methods.
- 3.6.A.1When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
- 3.6.A.2When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object.
- 3.6.A.3Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method’s enclosing class.
-
3.7 Class Variables and Methods 2 objectives
3.7.A Develop code to define behaviors of a class through class methods.
- 3.7.A.1Class 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.
- 3.7.A.2Class methods can access or change the values of class variables and can call other class methods.
3.7.B Develop code to declare the class variables that belong to the class.
- 3.7.B.1Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
- 3.7.B.2Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
- 3.7.B.3When a variable is declared final, its value cannot be modified.
-
3.8 Scope and Access 1 objective
3.8.A Explain where variables can be used in the code.
- 3.8.A.1Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be public or private.
- 3.8.A.2When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.
-
3.9 this Keyword 1 objective
3.9.A Develop code for expressions that are self-referencing and determine the result of these expressions.
- 3.9.A.1Within an instance method or a constructor, the keyword this acts as a special variable that holds a reference to the current object— the object whose method or constructor is being called.
- 3.9.A.2The keyword this can be used to pass the current object as an argument in a method call.
- 3.9.A.3Class methods do not have a this reference.
Where you are
Not startedAnswer the checks above whenever you like. They're not graded, and you can retry any of them.
Sources
- College Board — AP Computer Science A Course and Exam Description, Effective Fall 2025
AP Computer Science A · members' unit
Class Creation is behind a locked door
Units in AP Computer Science A are for people taking the course. Getting in takes a link or a key — signing in on its own doesn't do it.
What's in this unit · 17 min read
- 3.1 · Abstraction and program design
- 3.2 · Impact of program design
- 3.3 · Anatomy of a class
- 3.4 · Constructors
- 3.5 · Methods, and how to write them
- 3.6 · Passing and returning references
- 3.7 · Class variables and methods
- 3.8 · Scope and access
- 3.9 · The this keyword
- The projects · Monster, then MonsterBattle
- Where this goes next
23 quick checksobject reference diagramsobject instantiation yarddebugging drills
1 Sign in
With your school Google account. This is how your work reaches the gradebook — it doesn't open the unit by itself.
A key unlocks this browser and keeps your progress here; signing in keeps it with you across devices. Either way the key itself is only ever checked as a hash. Manage all of this on your account, read what signing in stores, or go back to AP Computer Science A.