Classes And Objects - Constructors
Constructors
First, we have to create a new instance of the Dog class. This is done through constructors. Java actually provides a default constructor, but we can still define our own, and we should if we want to specify how we initialize an object:
The constructor looks almost like a method, but it doesn't have a return type, and its name must match the class name. Notice how inside the constructor, we must use this.name to refer to the new class instance's name field. This is required because the name parameter in the constructor has the same name as the field, so we need to specify which variable we're talking about. Now, we can create a new Dog object and interact with it:
A class can have any amount of constructors, each taking specific combinations of parameters. For example, we can add a constructor that only takes a name, and sets a default age:
Now, we can create a Dog object with just a name:
This all looks great! We can create a Dog by specifying its name and age, or just its name. But what about the bark() method we defined earlier?
ByteBrawl
0