Core Java

What is a Constructor in Java

In this article, we are going to explore what is a constructor in Java, why it is used, how it is formed, what are the rules applied to create one, we will see different types of constructors, constructor chaining, and overloading.

1. What is a Constructor in Java?

what is a constructor in java

The constructor is a piece of code that runs whenever the compiler finds the new keyword to construct the object of a class. The object cannot create without invoking a constructor. There are two main rules of creating a constructor: firstly, its name is the same as a class in which it is declared and secondly, it does not have a return type.

A constructor is used to initialize the state of an object. Every class has a constructor including an abstract class even if it does not explicitly define in a class. In that case, the compiler will add a default no-argument constructor during compilation. Let’s have a look at a basic example:

Car.java

public class Car {

	// constructor
	Car(){}
	
	public static void main(String[] args) {
		//initializing object by calling no argument constructor
		Car car = new Car();
	}	
}

The first thing to notice it looks like a method. However, it does not have a return type. The object of a class Car is initialized by calling Car() constructor with new keyword.

The constructor can have any access modifier public, protected, and private. In the above example, no access modifier is given. so the compiler will take as a default package visibility. Moreover, a constructor cannot be marked as static as it used to initiate an object and final or abstract as it cannot be overridden.

Legal and illegal constructor declarations

int Car() {} // it is considered as a method, so compiler asks for a return value
void Car() {}  //it is a method not constructor
final Car() {} // Illegal modifier, constructor cannot be final
static Car() {} // Illegal modifier, constructor cannot be static
Car(int a); // Illegal - compiler consider it as a method, so it asks for a body instead of a semicolon 

private Car() {}    //Legal modifier
protected Car() {}  //Legal modifier
Car(int a) {}       //Legal 
Car() {}            // Legal

2. Types of Constructors

There are three types of Constructors:

  • Default
  • No Argument
  • Parametrized

2.1 Default

A default constructor is a no-argument constructor add by the compiler on behalf of the user if the compiler does not find any in class. Let have a quick example:

Car.java

public class Car {
	public static void main(String[] args) {
		//calling default argument constructor
		Car car = new Car();
	}
}

In the preceding example, no constructor is defined and still, the object is created by calling the default constructor.

2.2 No-Argument

No-argument constructor is often confused with the default constructor but both are different. No argument constructor is defined in a java class .java file by developer/user whereas the default constructor is added by compiler in a .class version of a class. This constructor can be empty or use to initialize some default values to variables.

2.3 Parametrized

A constructor can have zero or more parameters that are used to initialize the state of an object. In the below example, the Person class has a constructor Person(String name, int age) that takes two arguments and create an object. Furthermore, it initializes values to instance variables.

Person.java

public class Person {

	private String name;
	private int age;

	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	
	public static void main(String[] args) {
		//calling parameterized constructor
		Person person = new Person("John", 22);
	}

}

What if no argument constructor calls on a Person class, like:

Person person = new Person();

Compiler fails to compile as it is not defined in a class. To call no-argument constructor, it must be defined explicitly. The compiler only adds default constructor when no constructor is defined in a class and Person class has one parametrized constructor.

3. super()

The super() keyword is used to call the superclass constructor. It must be the first statement of a constructor body unless the constructor calls the overloaded constructor of its class. To call a parameterized superclass constructor, super is called with arguments like super("a"). Let’s have a look at an example:

Person.java

public class Person {
	private String name;
	private int age;
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
}

class Student extends Person {
	private int studentId;
	private String batch;	
	public Student(String name, int age, int studentId, String batch) {
		super(name, age);
		this.studentId = studentId;
		this.batch = batch;
	}
	public static void main(String[] args) {
		Student student = new Student("John", 22, 101, "VI");
	}
}

In the preceding example, Student is a subclass of Person. The Student parametrized constructor Student(String name, int age, int studentId, String batch) calls its superclass parameterized constructor super(name, age) to initialize state.

what if Student(String name, int age, int studentId, String batch) calls super with no parameter like super()

You cannot call super() because Person class does not define no argument constructor.

4. Constructor Chaining

whenever new is called with a constructor, it will call its superclass constructor implicitly unless it calls its overloaded constructor using this(). Let’s have a look at this example:

The class Student extends with class Person, and the class Person extends with the class Object implicitly

Student -> Person -> Object

Every constructor calls its superclass constructor, So when Student class constructor invokes, it calls Person class constructor and Person class constructor calls Object class constructor then it initializes its state and returns control to Person class constructor than its instance variables are initialized(if any) than control returns to Student class controller to initialize its state

Object()
Person() calls Object()
Student() calls Person()
calls new Student()
Constructor Calling Stack

5. Constructor Overloading

Constructor overloading means the different versions of the constructor having different parameters. The idea behind different constructors is to provide multiple ways to create an object from different parameters. Let’s have a look at an example:

Box.java

public class Box {

	private String color;
	private int height;
	private int width;
	private int length;
	
	public Box(){}
	
	public Box(String color){
		this.color = color;
	}
		
	public Box(int height, int width, int length){
		this.height = height;
		this.width = width;
		this.length = length;
	}
	
	public Box(String color, int height, int width, int length){
		this(height, width, length);
		this.color = color;
	}
	
	@Override
	public String toString() {
		return "Color:"+color+", height:"+height+", width:"+width+", length="+length;
	}
	
	public static void main(String[] args) {
		Box box1 = new Box();
		System.out.println(box1);
		
		Box box2 = new Box("Yellow");
		System.out.println(box2);
		
		Box box3 = new Box("Red", 2, 3, 4);
		System.out.println(box3);
		
		Box box4 = new Box(2, 3, 4);
		System.out.println(box4);
	}
}

In the preceding example, Box class has four overloaded constructors,

  1. First is no-argument constructor, it can be used to create an object without any explicit values.
  2. The Box(String color) constructor initializes an object by initializing color value only.
  3. The Box(int height, int width, int length) constructor initializes an object using height, width and length variables.
  4. The Box(String color, int height, int width, int length) constructor initializes an object from color, height, width and length.

6. Copy Constructor

Copy constructor allows creating a new object with an existing object state by passing the same class object as an argument in a constructor.

House.java

public class House {

	private int yards;
	private int roomsCount;
	private boolean hasGarden;
	
	/**
	 * This constructor takes yards, roomsCount and hasGarden values and
	 * assign then to create a new object
	 * 
	 * @param yards
	 * @param roomsCount
	 * @param hasGarden
	 */
	public House(int yards, int roomsCount, boolean hasGarden) {
		this.yards = yards;
		this.roomsCount = roomsCount;
		this.hasGarden = hasGarden;
	}
	
	/**
	 * Copy constructor: taking the object of the same class as a parameter and assign its 
	 * instant variable values to create a new object
	 * @param house
	 */
	public House(House house) {
		this.yards = house.getYards();
		this.roomsCount = house.getRoomsCount();
		this.hasGarden = house.isHasGarden();
	}

	public static void main(String[] args) {
		House house1 = new House(240, 3, true);
		System.out.println(house1);
		House house2 = new House(house1);
		System.out.println(house2);
	}
	
	@Override
	public String toString() {
		return "Yards:"+getYards()+", total rooms:"+getRoomsCount()+", has garden:"+isHasGarden();
	}
	
	public int getYards() {
		return yards;
	}

	public void setYards(int yards) {
		this.yards = yards;
	}

	public int getRoomsCount() {
		return roomsCount;
	}

	public void setRoomsCount(int roomsCount) {
		this.roomsCount = roomsCount;
	}

	public boolean isHasGarden() {
		return hasGarden;
	}

	public void setHasGarden(boolean hasGarden) {
		this.hasGarden = hasGarden;
	}	
}

7. Download the Source Code

All of the above examples of constructors are packaged into a project, and can be downloaded from below link.

Download
You can download the full source code of this example here: What is a Constructor in Java

Sadia Sher

This is Sadia (Backend Developer-Java). I have graduated from Jinnah University For Women, Karachi, Pakistan. Coding is my first love, therefore I am a developer. Why Java? Because It has been found as the most diverse language with plenty of APIs, frameworks and integration support. Other than this I am a Yogi. Ever since I practice yoga my lifestyle changes to morning bird. This strengthens my core just as JVM strengthens Java.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button