Lesson: Constructors

Overview: 
Explore object constructor methods.
Objectives: 

Understand what an object constructor is and how it is used.

Content: 

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. Constructor(s) are used to initialize 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 and we will add a 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 two constructors, the first with no parameters which would create a Dog object with the fields set to empty strings. If we use this constructor the bark() method won't fail because we directly initialized the fields. If we use the second constructor we create the Dog object with the breed and name fields set to our desired values on one statement.

If you omit a constructor, the Java compiler creates one for you in the class file. That default constructor has no parameters and no code so it really does nothing, like the first constructor in our Dog class above.

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

 

Navigation: