8. Constructors

8.1. Constructor: Introduction

A constructor is to set the initial state of an object, when the object is created by using the new operator.

General syntax of the constructor declaration is as follows:

<accessibility modifier> <class name> (<formal parameter list>) <throws clause> // Constructor header
{ // Constructor body
<local variable declarations>
<nested local class declarations>

The above constructor declaration syntax can be divided into

Rules of constructor declaration:

Let’s build a new class Vehicle and take a closer look at some of the elements in constructor header and constructor body.

			package javatutorial;

			 * Class to understand/identify the following elements in constructor declaration
			 * •	Constructor header
			 * 		o	accessibility modifier: can be public, private, protected etc
			 * 		o	class name: name of the class
			 * 		o	formal parameter list: list of formal parameters
			 * •	Constructor body
			 * 		o	local variable declarations
			 * 		o	statements: can be declaration, control flow or expression statement
			 *  @author f5java.com   
			public class Vehicle {
				long vehRegistrationNumber;
				int noOfWheels;
				int horsePower;
				String color;
				// Constructor
				public Vehicle(	long vehRegistrationNumber,	int noOfWheels,	int horsePower,	String color){
					String message = "Your vehicle is " + color + "color";
					// Below statements are assignment statements
					this.vehRegistrationNumber = vehRegistrationNumber;
					this.noOfWheels = noOfWheels;
					this.horsePower = horsePower;
					this.color = message;		
				// 1. Identify parts of constructor header
				// accessibility modifier is public
				// class name is Vehicle
				// formal parameters are: vehRegistrationNumber, noOfWheels, horsePower, color
				// 2. Constructor body consists of
				// local variable: message
				// constructor body consists of 4 assignment statements
				 * Displays the default values initialized by the constructor
				public void printDefaultValues(){
					System.out.println("Vehicle Registration Number: " + vehRegistrationNumber);
					System.out.println("No of Wheels: " + noOfWheels);
					System.out.println("Vehicle Horse Power: " + horsePower);
					System.out.println("Vehicle Color: " + color);
				public static void main(String[] args) {
					// Instantiate and call the method
					Vehicle vehicle = new Vehicle(12376678, 4, 380, "Blue");
					System.out.println("Printing the default values set by the constructor");