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.
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
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!
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:
Just like with other methods,
classes can provide multiple constructors as long as they accept different parameters: