A class is the blueprint that defines what data and behavior its objects have, and an object is one instance built from it with new and a constructor call, such as new Counter(5). A variable of a class type holds a reference to an object, not the object itself, or null when it refers to no object. Calling an object's method through null throws a NullPointerException, and copying a reference makes two variables refer to the same object.
Quick check
After int a = 4; int b = a; a = 9; what does b hold?Show answerHide answer
- Assigning one
intto another copies the value, so changingalater does not changeb.
- Assigning one
One cookie cutter makes twelve cookies. Is the cutter more like a class or an object?Show answerHide answer
A class. The cutter is the pattern, and each cookie is one object made from it.
Know these already? Jump to the practice questions
What you'll be able to do
- Explain the difference between a class and an object.
- Identify a statement that correctly creates an object with
newand a constructor. - Determine which object each reference variable refers to after a sequence of assignments.
- Predict when a line throws a
NullPointerException. - Determine the output when two variables refer to the same object.
Key terms
Class
A blueprint that defines the data and the methods every object of that type has.
- In plain English
- The design that objects are built from.
- Don't write
- "A class and an object are the same thing."
Object
One instance of a class, with its own values for the data the class defines.
- In plain English
- One thing built from the design.
- Don't write
- "Every object of a class shares one set of values."
Constructor
Code with the same name as the class that new runs to give a new object its starting values.
- In plain English
- The setup step for each new object.
- Don't write
- "Declaring
Counter c;runs the constructor."
Reference
The value a variable of a class type holds: it locates an object, or it is null when there is no object.
- In plain English
- An arrow from the variable to the object.
- Don't write
- "
Counter b = a;copies the object."
What is the difference between a class and an object?
A class describes a kind of thing; an object is one actual thing of that kind. This Counter class is used throughout the note. Writing classes like it is Unit 3; here you only use it.
public class Counter
{
private int count;
public Counter(int start) { count = start; }
public void click() { count++; }
public int getCount() { return count; }
}
The class says every Counter has a count, a constructor that sets it, a click method that adds 1 and a getCount method that returns it. Each object gets its own count:
Counter a = new Counter(5);
Counter b = new Counter(5);
a.click();
Now a's object has a count of 6 and b's still has 5, because they are two separate objects. Calling methods is covered in the note on calling methods and method signatures.
Check yourself
Show answerHide answer
No. Each object has its own count, so clicking one leaves the other unchanged.
How do you create an object?
Counter c = new Counter(5); does three things:
Counter cdeclares a variable that can refer to aCounter.new Counter(5)creates the object and runs the constructor with the argument 5, so the count starts at 5.=stores a reference to the new object inc.
The constructor has the same name as the class, and the arguments must match one of the class's constructors: Counter has only Counter(int start), so new Counter() would not compile.
Declaring a variable creates no object. Only new does, so Counter c; on its own gives you a variable with nothing to refer to yet.
Learn this: new and constructor calls are Java syntax, not on the Java Quick Reference.
Check yourself
Show answerHide answer
new. A declaration alone creates only the variable.
What does a reference variable hold, and what is null?
A primitive variable such as an int holds its value directly. A variable of a class type holds a reference, which locates the object somewhere else in memory.
null is the reference that refers to no object. Counter d = null; compiles, and copying or comparing d is fine. But calling a method through it, as in d.click();, has no object to act on, so it throws a NullPointerException when that line runs and the program stops there.
Key idea
Calling an object's method needs an object: doing it through a variable that holds null throws a NullPointerException.
Check yourself
Show answerHide answer
d.click();. Copying null into e is allowed; calling a method through null is not.
What happens when two variables refer to the same object?
Assigning one reference variable to another copies the reference, not the object. After Counter b = a; there is one object with two names, and a and b are aliases. A change made through either one is seen through both.
| Statement | a refers to | b refers to | Count of object 1 |
|---|---|---|---|
Counter a = new Counter(2); | object 1 | none | 2 |
Counter b = a; | object 1 | object 1 | 2 |
b.click(); | object 1 | object 1 | 3 |
So a.getCount() now returns 3. Compare this with int variables, where int y = x; copies a value and the two stay separate.
If a is later given a new object, as in a = new Counter(0);, only a moves; b still refers to object 1. For references, a == b is true only when both refer to the same object.
Check yourself
Show answerHide answer
aandbrefer to the same object, so the click throughbchanged the objectarefers to.
Worked example 1: Trace two separate objects
Question: What is printed when this code segment runs?
public class Counter
{
private int count;
public Counter(int start) { count = start; }
public void click() { count++; }
public int getCount() { return count; }
}
Counter a = new Counter(3);
Counter b = new Counter(3);
a.click();
a.click();
b.click();
System.out.println(a.getCount());
System.out.println(b.getCount());
What tells you the method
Each variable is given its own new, so there are two objects: trace one column per object.
Step 1: Trace the objects.
Statement Object 1 ( a)Object 2 ( b)both created 3 3 a.click();4 3 a.click();5 3 b.click();5 4 WhyTwo calls to
newmake two objects, each with its owncount.Step 2: Print the counts.
5, then 4.
WhygetCountreturns the count of the object the variable refers to.
Check it
The objects started at 3 + 3 = 6 and received three clicks in total, so the counts must add to 9, and 5 + 4 = 9.
Answer
5 then 4, one per line.
Worked example 2: Follow an alias after reassignment
Question: What is printed when this code segment runs?
public class Counter
{
private int count;
public Counter(int start) { count = start; }
public void click() { count++; }
public int getCount() { return count; }
}
Counter p = new Counter(10);
Counter q = p;
q.click();
p = new Counter(0);
p.click();
System.out.println(p.getCount());
System.out.println(q.getCount());
What tells you the method
A reference is copied and then one variable is reassigned: track which object each variable refers to, not just the counts.
Step 1: Trace references and counts.
Statement pqObject 1 Object 2 p = new Counter(10)obj 1 none 10 Counter q = p;obj 1 obj 1 10 q.click();obj 1 obj 1 11 p = new Counter(0);obj 2 obj 1 11 0 p.click();obj 2 obj 1 11 1 WhyLine 4 moves only
pto a new object;qkeeps referring to object 1.Step 2: Print the counts.
pgives 1 andqgives 11.WhyThe click on line 3 changed object 1, which
qstill refers to.
Check it
Object 1 was clicked once, from 10 to 11, and object 2 once, from 0 to 1.
Answer
1 then 11, one per line.
Worked example 3: Find where null breaks the code
Question: What happens when this code segment runs?
1: String name = "Ada";
2: String other = null;
3: String copy = name;
4: System.out.println(copy.length());
5: System.out.println(other.length());
6: System.out.println(name.length());
- A) It prints 3, then 0, then 3.
- B) It prints 3, then throws a
NullPointerExceptionat line 5. - C) It throws a
NullPointerExceptionat line 3. - D) It does not compile, because line 2 gives a
Stringvariable the valuenull.
What tells you the method
A variable holds null: find the first line that calls a method through it.
Step 1: Check lines 1 to 4.
Line 2 compiles, because any class-type variable can hold
null. Line 3 copies a reference to "Ada", and line 4 prints its length, 3.WhyStoring or copying a reference never needs an object.
Step 2: Check line 5.
otherisnull, soother.length()has no object and throws aNullPointerException. Line 6 never runs.Whynullis not an empty string; it is no object at all.
Check it
If line 2 were String other = "";, line 5 would print 0. Option A describes that different code.
Answer
B
Your turn
Question: What is printed when this code segment runs?
public class Counter
{
private int count;
public Counter(int start) { count = start; }
public void click() { count++; }
public int getCount() { return count; }
}
Counter m = new Counter(1);
Counter n = m;
Counter k = new Counter(1);
n.click();
k.click();
k.click();
System.out.println(m.getCount());
System.out.println(m == n);
System.out.println(m == k);
Step 1: Count the objects.
There are two calls to
new, so two objects:mandnshare object 1, andkhas object 2.Step 2: Your go: trace the clicks and decide the three printed lines.
Show the full solutionHide the solution
Step 2. n.click() raises object 1 from 1 to 2, so m.getCount() returns 2. The clicks on k change only object 2. m == n is true, because both refer to object 1; m == k is false, because they refer to different objects.
Answer: 2 then true then false, one per line.
Traps
Trap
Counter b = a; makes a copy of the object.
It seems right because int y = x; copies a value. But a class-type variable holds a reference, so the assignment copies the reference, and both names now lead to one object.
After Counter a = new Counter(0); Counter b = a; b.click(); how many Counter objects exist?
One. new ran once, and a and b both refer to it.
Trap
Declaring Counter c; creates a Counter object.
It seems right because declaring an int gives you somewhere to store a number. But a class-type variable only stores a reference; no object exists until new creates one.
Which part of Counter c = new Counter(2); creates the object?
new Counter(2). The declaration Counter c only creates the variable.
Trap
A variable that holds null behaves like an empty object.
It seems right because null sounds like "nothing in it". But null means no object at all, so calling a method through it throws a NullPointerException.
String s = null; What happens when s.length() runs?
It throws a NullPointerException; it does not return 0.
What's examined
On the AP® Computer Science A exam, Unit 1 object questions appear in multiple choice, for example what is printed when two variables share one object. In free response, you create objects with new and call their methods in the code you write.
Practice questions
The Counter class below is for questions 1 to 5.
public class Counter
{
private int count;
public Counter(int start) { count = start; }
public void click() { count++; }
public int getCount() { return count; }
}
- Recall Which statement creates a
Counterobject whose count starts at 5 and stores a reference to it in a new variable?
- A)
Counter c = new Counter(5); - B)
Counter c = Counter(5); - C)
Counter c = new Counter; - D)
Counter c = 5;
Show answer
Answer: A. new creates the object, Counter(5) calls the constructor with 5, and = stores the reference in c.
Why the others are wrong:
- B leaves out
new, so no object is created and it does not compile. - C leaves out the parentheses and the argument the constructor needs.
- D tries to store an
intin aCountervariable, as if it were a primitive type.
- Apply What is printed when this code segment runs?
Counter s = new Counter(7);
Counter t = new Counter(7);
Counter u = s;
u.click();
t.click();
s.click();
System.out.println(s.getCount());
System.out.println(t.getCount());
Show answer
Answer: 9 then 8, one per line.
Marking points:
sandurefer to the same object, which is clicked twice: 7, 8, 9.trefers to a separate object, clicked once: 7, 8.
- Apply How many
Counterobjects does this code segment create?
Counter a = new Counter(0);
Counter b = a;
Counter c = new Counter(0);
Counter d = c;
Counter e = null;
Show answer
Answer: 2
Marking points:
- Only
newcreates an object, and it appears twice. banddcopy references, anderefers to no object.
- Exam-style
Counter r = null;has run. Which statement throws aNullPointerExceptionwhen it runs next?
- A)
Counter s = r; - B)
r = new Counter(4); - C)
System.out.println(r == null); - D)
r.click();
Show answer
Answer: D. It calls a method through r, which refers to no object.
Why the others are wrong:
- A only copies the
nullreference intos. - B gives
ra new object, which is always allowed. - C compares references without calling a method, so it prints
true.
- Exam-style This code segment is meant to keep two separate scores, so that it prints 1 and then 1. Give the number of the line that stops it working.
1: Counter home = new Counter(0);
2: Counter away = home;
3: home.click();
4: away.click();
5: System.out.println(home.getCount());
6: System.out.println(away.getCount());
Show answer
Answer: Line 2.
Marking points:
- Line 2 makes
awayan alias ofhome, so both clicks change one object and the code prints 2 twice. - Changing line 2 to
Counter away = new Counter(0);gives two objects, each clicked once.
- Recall Which keyword creates a new object in Java?
- A)
class - B)
null - C)
new - D)
final
Show answer
Answer: C. new creates an object and runs its constructor.
Why the others are wrong:
- A begins a class definition, the blueprint, not an object.
- B is the reference to no object.
- D marks a variable that can be assigned only once.
- Recall Name the exception thrown when a method is called through a variable that holds
null.
Show answer
Answer: NullPointerException
Marking points:
nullrefers to no object, so there is nothing for the method to act on.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- A class is the design; each object made from it with
newhas its own data. new ClassName(arguments)creates an object and runs the matching constructor.- A class-type variable holds a reference, and
nullmeans it refers to no object. - Calling an object's method through
nullthrows aNullPointerException. - Assigning one reference variable to another creates an alias, so both see the same object's changes.