Object Creation and Storage (Instantiation)
Skill 2.B
Big idea: new plus a constructor call builds an object. Which constructor runs depends on the arguments you pass.
- Identify, using its signature, the correct constructor being called.
- Develop code to declare variables of the correct types to hold object references.
- Develop code to create an object by calling a constructor.
Constructors
A constructor has the same name as the class and no return type. It sets up a new object's initial state. A class can have several constructors (overloading), each with a different parameter list.
CodePoint origin = new Point();
Point p = new Point(3, 4);
System.out.println(origin.getX() + "," + origin.getY());
System.out.println(p.getX() + "," + p.getY());Output0,0 3,4
Declaring vs. creating
Point p; only declares a variable. No object exists until new runs. A variable set to null refers to no object.
Arguments to a constructor are passed by value and must match a constructor's parameters in number, order, and type, just like a method call.
Point a; // declared, no object
Point b = null; // explicitly no object
Point c = new Point(1, 2); // object created- Constructors have the class's name and no return type.
- A constructor signature is the class name plus the ordered parameter types; constructors can be overloaded.
- Objects are created with
newfollowed by a constructor call. - A reference variable holds an object reference or
null.
new Point(3)won't compile if no constructor takes one int.- Declaring a variable doesn't create an object.
Given constructors Book(String title) and Book(String title, int pages), which one runs for new Book("Dune", 412)?
Show answer
Book(String, int), because the arguments are a String and an int.