1.13 - Object Creation and Storage (Instantiation)
A class contains constructors, which get called to create objects. A constructor always shares its name with the class it belongs to.
A constructor signature is the constructor’s name (same as the class name) plus the ordered list of parameter types.
The parameter list in a constructor’s header lists the type and name of each value that gets passed in. The signature only keeps the types, in order. So a header like
public Book(String t, int p) has the signature Book(String, int).Constructors can be overloaded too, just like methods, as long as they have different signatures.
A reference type variable holds either an object reference, or
null if there’s no object.You typically create an object using the keyword
new followed by a call to one of the class’s constructors.public class Dog { String name; Dog(String dogName) { // constructor name = dogName; } } Dog myDog = new Dog("Rex"); // creating an object
Declaring a variable doesn’t make an object. Only
new does:Dog myDog; // a variable that can refer to a Dog, but there's no Dog yet myDog = new Dog("Rex"); // now there is one Dog other = null; // null: no object at all
Java figures out which constructor to run by matching the arguments to the signatures, just like with overloaded methods:
public class Book { private String title; private int pages; public Book() { // Book() title = "Untitled"; pages = 0; } public Book(String t) { // Book(String) title = t; pages = 0; } public Book(String t, int p) { // Book(String, int) title = t; pages = p; } }
Book b1 = new Book(); // calls Book(), title is "Untitled" Book b2 = new Book("Wings"); // calls Book(String) Book b3 = new Book("Wings", 240); // calls Book(String, int) Book b4 = new Book(240, "Wings"); // won't compile, there's no Book(int, String)
Parameters let constructors accept values that set up the object’s initial state. A constructor argument is the actual value passed in when the constructor is called, and just like methods, this uses call by value, meaning the parameters get copies of the arguments.
The arguments have to be compatible with the constructor’s parameter list in number and order. That’s why
new Book(240, "Wings") above doesn’t compile: the only constructor with two parameters expects a String first, then an int.When a constructor gets called, it interrupts sequential execution the same way a method does, runs its statements, then hands control back to right after where it was called.
public class Pet { private String name; public Pet(String n) { System.out.println("making " + n); name = n; } } // in main: System.out.println("start"); Pet p = new Pet("Kiwi"); System.out.println("done");
Output:
start making Kiwi done