AP Computer Science A · Unit 1 lecture · Part 8 of 11 · 9 min

1.12 Objects: instances of classes · 1.13 Object creation and storageBlueprints and the things built from them

Mr. Thompkins
So far our variables held numbers. Now they get to hold things: a bottle, a bank account, a song. The class describes the thing, and every object you build from it gets its own copy of the data.

A class is like a blueprint. It describes what every object of that kind stores (its attributes) and what it can do (its behaviors), but it isn't an object itself. An object is a specific instance of a class, with its own values for every attribute. One Bottle blueprint can produce a 500 ml bottle that's empty and a 750 ml bottle that's a third full. Each object has its own state, and changing one doesn't change the other.

Here's a class someone has written for you. You don't need to know how to write classes yet (that's Unit 3), but you do need to read one: find the constructors, and find each method's return type and parameters.

1public class Bottle2{3    private int ml;          // how much is inside14    private int capacity;    // the most it can hold156    public Bottle(int cap)27    {8        capacity = cap;9        ml = 0;10    }1112    public Bottle(int cap, int start)213    {14        capacity = cap;15        ml = start;16    }1718    public void add(int amount)   { ml += amount; }319    public void drink(int amount) { ml -= amount; }320    public int getMl()            { return ml; }421    public int getCapacity()      { return capacity; }42223    public double fractionFull()524    {25        return (double) ml / capacity;526    }27}
  1. line 3-4 Fields: the data every Bottle object keeps
  2. line 6-12 Two constructors: overloaded, run by new
  3. line 18-19 void methods: they change the object
  4. line 20-21 Getters: they return a value, change nothing
  5. line 23-25 Returns a double: how full, from 0.0 to 1.0
The Bottle class. Its two attributes are private, so code outside the class can only reach them through its methods.
?Wait, what does private mean?
private means only code inside the class can use that field or method directly. Code outside the class, like your main method, can't write a.ml. It has to use the public methods instead, like a.getMl(). That keeps an object's data safe from careless changes.

A class defines a new type, so you can declare variables of that type: Bottle a;. Every Java class is also a subclass of Object, the built-in class at the top of every family tree.

Creating objects with new

You create an object with the keyword new followed by a call to a constructor: new Bottle(500). A constructor is a special block of code that sets up a new object's starting state. It has the same name as the class and no return type, not even void. Calling new does three things: it makes space for a brand-new object, it runs the constructor to set its attributes, and it gives back a reference to the new object.

Constructors can be overloaded, just like methods. Bottle has two: Bottle(int cap) starts the bottle empty, and Bottle(int cap, int start) starts it with start ml inside. The arguments you pass to new must match one of the constructor signatures, in number, order and type. If no constructor matches, the code doesn't compile.

class Bottlethe blueprintfields: ml, capacitynew Bottle(500)new Bottle(750, 250)ml 0, capacity 500object 1ml 250, capacity 750object 2
One class, two objects. Each new builds a separate object with its own values for ml and capacity.

Where objects live

Bottle a = new Bottle(500); stores a reference in a: an arrow to the object. The object itself lives somewhere else in memory. A reference variable can also hold the special value null, which means "no object at all." Bottle spare = null; declares a variable that doesn't refer to anything yet.

?Wait, what's a reference again?
A reference is how Java finds an object: think of it as an arrow from the variable to the object. Primitive variables (int, double, boolean) hold their values directly. Variables of a class type, like String or Bottle, hold a reference to an object, or null if there isn't one.
Pause and think

How many Bottle objects exist after these four lines?

Bottle a = new Bottle(500);
Bottle b = a;
Bottle c = new Bottle(300);
Bottle d = null;
I thought about it. Show me
Two. Count the word new: it appears twice, and only new creates an object. b = a copies the arrow, so b refers to the same object as a. d is null, so it refers to no object at all.
Which constructor calls work?

Using the Bottle class above, decide whether each line compiles.

(a) Bottle w = new Bottle(500);
(b) Bottle x = new Bottle(750, 250);
(c) Bottle y = new Bottle();
(d) Bottle z = new Bottle(1.5);
(e) Bottle v = Bottle(500);
  1. (a) compiles. One int argument matches Bottle(int cap).
  2. (b) compiles. Two ints match Bottle(int cap, int start).
  3. (c) does not compile. Bottle has no constructor with zero parameters, so nothing matches.
    Why?
    Java only gives a class a free no-argument constructor if the class writes no constructors at all. Bottle writes two.
  4. (d) does not compile. 1.5 is a double, and a double can't be passed to the int parameter cap.
  5. (e) does not compile. Without new, Java reads Bottle(500) as a call to a method named Bottle, and there isn't one. Objects are created only with new.

Answer: Only (a) and (b) compile.

Stuck? Get a hint
  1. List the constructors Bottle has: how many parameters does each take, and of what types?
  2. For each line, count the arguments and check their types against a constructor.
  3. Is new there? Without it, no object is created.
Check yourself
Which statement is true after this code runs?
Bottle p = new Bottle(500);
p = new Bottle(750);
Bottle q = p;
  1. AThere is one Bottle object, and both p and q refer to it.
  2. BThere are two Bottle objects, and q refers to the second one.
  3. CThere are two Bottle objects, and both p and q refer to the second one.
  4. DThere are two Bottle objects, and p refers to the first one.
Show the answer

C. Two news make two objects. q = p copies p's arrow, so q points to the second object too, and nothing refers to the first one anymore. Choice D is the trap: assigning p a new object moves p's arrow away from the first object.

  • A class is a blueprint and a type. An object is one instance, with its own state.
  • new runs a constructor and returns a reference to a brand-new object. Constructors have the class's name and no return type.
  • Arguments to new must match a constructor signature. No match, no compile.
  • Reference variables hold an arrow to an object, or null for none.