Kotlin
Java

Constructors
Java

Created By: Geoffrey Challen
/ Updated: 2021-09-18

Let's continue our discussion of Java objects. Remember that bit of syntax that looked like a method call when we create a new Java object? Well, it was! Next we'll talk about what it does.

Constructors

Previously when we created instances of our new object classes, we used new followed by something that looked like a method call to a function accepting no parameters:

It turns out that this is exactly what follows new. Usually when we create a new object we want to set the fields on it right away. Rather than doing this in the fairly clumsy way shown above, Java provides a better alternative. Let's look at it together!

Write a first constructor for the Person class shown above. Emphasize that the constructor is just code, identify the naming convention, and point out that it "returns" a new instance of the class.

Constructor Semantics

There are a few things to keep in mind about constructors.

First, they must have the same name as the class and cannot declare a return value:

You can, however, use return in a constructor if you want to skip some parts of the initialization in certain cases:

Finally, we don't need to declare a constructor. If we don't, Java will include a default constructor that takes no arguments. Let's see how that works:

Show how the default constructor works by replacing it with its equivalent. Point out that once you declare a constructor you lose the default constructor.

Overloaded Constructors

Just like with other methods, classes can provide multiple constructors as long as they accept different parameters:

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough