Instructional Material: Constructors

Printer-friendly version

Objects have special kind of method called a constructor. A constructor is an optional method that is called when a new instance of an object is created with the new keyword. Constructors are used to initialize the fields of the new object instance. A constructor looks like a method except that it has no return data type (including void) and has the same name as the class. A constructor can have a parameter list and a class can have more than one constructor by varying the parameter list. Lets look at our Dog class from the previous lesson:

We see that the fields breed and name are not initialized. This would lead to a run time error (called an exception) if we called the bark() method without first putting something in the breed and name fields. We can fix this with direct initialization of the fields or with a constructor method, and we will add a second constructor that allows us to set the breed and name fields when we create a new Dog object:

 So in another place in your code you would write:

We have added three constructors, the first with no parameters which would create a Dog object with the breed field set to an empty string. We directly set the name field to an empty string. When we create an instance of this class, the bark() method won't fail because the constructor is called and initializes the breed field and the name field is initialized when the object is created by Java. If we use the second constructor when we create the Dog object instance, the breed field is set with our desired value. If we use the third constructor when we create the Dog object the breed and name fields are set to our desired values on one statement.

If you omit a constructor, the Java compiler creates one for you internally. That default constructor has no parameters and no code so it really does nothing.

Note that the second constructor shows the use of the this keyword again and also how you can do it without using this.

Here is a video about constructors.

Here is the example on CodingGround. Modify the example to add an age variable (field) and a constructor that allows you to initialize the age (along with breed and name) when creating a new Dog object instance.

 

 

Material Type: 
Lecture/Presentation
Education Level: 
HW Platform: 
SW Platform: 
Interactivity Style: 
Audience: