Java – Constructors

  1. Introduction
  2. Constructor with no Arguments
  3. Parameterized Constructors
  4. Creating new Objects

1. Introduction

Constructors in Java are what we use to create new objects. Furthermore, you use a constructor on initialize new objects. Constructors have the same name as the class and not return type.

Generally, you assign initial values to instance variables using a constructor. But you can also perform some initial tasks required when a new object is created.

The code below give an example of a constructor.

public class Vehicle {
	public String make;
	
	public Vehicle(String make) { //constructor with one parameter
		this.make = make;
	}
}

We have two types of constructors in Java.

  • Constructor with no arguments
  • Parameterized constructor

2. Constructors with no arguments

These constructors require not arguments. In this way you can create an object even if you don’t have the attributes. Take for example, the code below.

public class Circle {
	int radius;
	
	public Circle () { //Constructor with no parameter
		radius = 50;
	}
}

The constructor for circle has no parameters. However, when a new circle is created, it automatically has a radius of 50. Therefore if you run the code below, you will have an output of 50.

public class Tester {

	public static void main(String[] args) {
		Circle circle = new Circle();
		
		System.out.println(circle.radius);
	}
}

3. Parameterized Constructors

Sometimes, you will need a constructor that accepts one or more parameters. You specify the parameter inside braces after the constructor name. An example is given below

public class Circle {
	public int radius;
	
	public Circle (int radius) { //Parameterized constructor
		this.radius = radius;
	}
}

In the same way, you can run create a circle using the code below.

public class Tester {

	public static void main(String[] args) {
		Circle circle = new Circle(50);
		
		System.out.println(circle.radius);
	}
}

Running the above code would also produce similar result to the previous one. 50 is printed out. But notice that in this constructor, you pass 50 as a parameter.

Finally bear in mind, that two or even more constructors can be in the same class.

4. Creating New Objects

Just as you know, objects are create from classes. You use the new keyword to create new objects from classes.

Note the three steps involved in creating new objects

  • Declaration: Here, you specify a variable name as an object type
  • Instantiation: You use the new keyword
  • Initialization: Assign initial values