Lesson 1.11 · Unit 1 · CED topics 1.12 and 1.13
Objects, classes, and constructors
Primitive types such as int hold a single value. Most of the data programmers work with is richer than that: a book has a title and a number of pages, a student has a name and a grade. Java models such things with classes and objects. This lesson covers what they are, how a variable refers to an object, and how to create one by calling a constructor. Writing your own classes comes in Unit 3. Here you learn to use classes that someone else wrote, which is how the exam presents them.
Learning objectives.
- 1.12.A. Explain the relationship between a class and an object.
- 1.12.B. Develop code to declare variables to store reference types.
- 1.13.A. Identify, using its signature, the correct constructor being called.
- 1.13.B. Develop code to declare variables of the correct types to hold object references.
- 1.13.C. Develop code to create an object by calling a constructor.
Essential knowledge.
- 1.12.A.1. An object is a specific instance of a class with defined attributes. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
- 1.12.A.2. A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without replacing these in the code. This creates an inheritance relationship from the subclasses to the superclass.
Outside the course: Designing and implementing inheritance relationships are outside the scope of the AP Computer Science A course and exam. - 1.12.A.3. All classes in Java are subclasses of the Object class.
- 1.12.B.1. A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
- 1.13.A.1. A class contains constructors that are called to create objects. They have the same name as the class.
- 1.13.A.2. A constructor signature consists of the constructor’s name, which is the same as the class name, and the ordered list of parameter types. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
- 1.13.A.3. Constructors are said to be overloaded when there are multiple constructors with different signatures.
- 1.13.B.1. A variable of a reference type holds an object reference or, if there is no object, null.
- 1.13.C.1. An object is typically created using the keyword new followed by a call to one of the class’s constructors.
- 1.13.C.2. Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
- 1.13.C.3. A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
- 1.13.C.4. A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.
Classes and objects
A class is the formal implementation, or blueprint, of the attributes and behaviors of an object. An object is a specific instance of a class with defined attributes. One Book class can produce many Book objects, each with its own title and number of pages.
To use a class, read its documentation. Here is the one we will use for the rest of the unit.
| Book constructor | What it does |
|---|---|
Book(String t) | creates a book titled t with 100 pages |
Book(String t, int p) | creates a book titled t with p pages |
| Book method | What it does |
|---|---|
String getTitle() | returns the title |
int getPages() | returns the number of pages |
void setPages(int p) | changes the number of pages to p |
boolean isLong() | returns true if the book has more than 300 pages |
Every class in Java is a subclass of the Object class. Classes can also be related to each other as a superclass and its subclasses, which share attributes and behaviors; designing and implementing those inheritance relationships is outside the scope of this course and the exam.
Variables that refer to objects
A variable of a primitive type holds the value itself. A variable of a reference type holds an object reference, which can be thought of as the memory address of the object. The object lives elsewhere; the variable only says where.
When no object has been assigned, a reference variable holds the special value null. The declaration alone does not create an object:
Book novel; // a variable that can refer to a Book, holding nothing yet Book empty = null; // explicitly refers to no object
Creating an object with a constructor
A class contains constructors, which are called to create objects. A constructor has the same name as the class. An object is typically created using the keyword new followed by a call to one of the class's constructors.
Book novel = new Book("Dune", 612);
Book pamphlet = new Book("Tips");
System.out.println(novel.getTitle() + " " + novel.getPages());
System.out.println(pamphlet.getTitle() + " " + pamphlet.getPages());
Dune 612 Tips 100
Parts of the creation statement, left to right: the type of the variable (Book), the variable name (novel), the assignment operator, the keyword new, the constructor call, and the list of arguments. Parameters allow constructors to accept values that establish the initial values of the object's attributes.
### Constructor signatures and overloading
A constructor signature consists of the constructor's name (the class name) and the ordered list of parameter types. When a class has several constructors with different signatures they are overloaded, and the arguments you supply decide which one runs: new Book("Tips") matches Book(String), and new Book("Dune", 612) matches Book(String, int). The arguments must be compatible in number, order, and type with the signature. As with methods, arguments are passed by call by value: the parameters are initialized with copies of the arguments.
A constructor call interrupts the sequential execution of statements. The program runs the constructor's statements first, and when the last one finishes, control returns to the point just after the call.
Which of these calls compile, and which constructor does each use?
| Call | Compiles? | Constructor |
|---|---|---|
new Book("Emma") | yes | Book(String) |
new Book("Emma", 474) | yes | Book(String, int) |
new Book(474, "Emma") | no | arguments in the wrong order |
new Book() | no | no constructor with no parameters |
new Book("Emma", 474.5) | no | a double cannot be passed for an int |
new Book("Emma", "474") | no | a String cannot be passed for an int |
Book b = new Book("Emma", 474);
System.out.println(b.isLong());
true
When a call does not compile, the reason is always one of three: wrong number of arguments, wrong order, or wrong type.
Two reference variables can refer to the same object. Assigning one reference variable to another copies the reference, not the object.
Book a = new Book("Atlas", 200);
Book b = a;
b.setPages(350);
System.out.println(a.getPages());
System.out.println(a == b);
350 true
There is only one Book object. b = a made both variables refer to it. The change made through b is visible through a, and a == b is true because the two references hold the same address (comparing references is the subject of Lesson 2.6). Creating a second book with new would give a different object and a different reference.
A reference variable that holds null has no object to work with.
Book shelf = null; System.out.println(shelf == null); System.out.println(shelf.getPages());
Exception in thread "main" java.lang.NullPointerException
Comparing a reference with null is safe, and it prints true here. Using a null reference to call a method is not: the program stops with a NullPointerException. A variable declared as Book shelf; and never assigned would not even compile if read, as in Lesson 1.4.
Expect questions that give a constructor list and ask which new call is valid or which constructor runs, questions that trace code in which two references share one object, and questions that end in a NullPointerException. State the relationship between a class and an object precisely: the class is the blueprint, an object is one instance. A reference-type variable holds an object reference or null, never the object itself. Inheritance is mentioned only as a fact; you are not asked to design it.
- Which statement correctly creates a
Booktitled "Poems" with 80 pages?A. Book b = Book("Poems", 80); B. Book b = new Book(80, "Poems"); C. Book b = new Book("Poems", 80); D. Book b = new Book("Poems");Show answer
C. Creation needs
new, and the arguments must matchBook(String, int)in order. A omitsnew, B swaps the arguments, and D uses the one-parameter constructor, which would give 100 pages. - What is printed?
Book x = new Book("Maps", 40); Book y = new Book("Maps", 40); System.out.println(x == y); Book z = x; System.out.println(x == z);Show answer
falseandtrue.newwas called twice, soxandyrefer to two different objects even though they look identical.z = xcopies the reference, soxandzrefer to the same object. - What is printed?
Book p = new Book("Notes"); Book q = p; q.setPages(p.getPages() + 50); System.out.println(p.getPages());Show answer
150.pandqshare one object. The object started with 100 pages, and thesetPagescall throughqraised it to 150. - What is the value of a reference variable that has been declared but has no object?
Show answer
null, the special literal that means the reference is not associated with any object. (A local variable that was never assigned cannot be read at all; a field or an explicit assignment givesnull.) - Why does
new Book()not compile for theBookclass above?Show answer
The class has only constructors with the signatures
Book(String)andBook(String, int). No constructor with an empty parameter list exists, so a call with no arguments matches nothing. - In one sentence each, what is a class and what is an object?
Show answer
A class is the blueprint that defines the attributes and behaviors; an object is one specific instance of the class, with its own values for the attributes.