Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Object-Oriented Programming

Understanding Constructors in Java

Constructors are the special method that is used to construct, create, or initialize the object. Whenever we create an object for a class, a constructor will be executed and the name of a constructor is similar to the class name.

Constructors are like methods even though they never have a return type & can’t return any value. They can have all the access levels, and they are also called non-static initializers, which are used to initialize an object & can’t be static.

Syntax:

class class_name
{
  className(){
	
  }
}

className rv=new className();

Example:

package oops;

public class A {
    A() {
        System.out.println("Running Constructor");
    }

    public static void main(String[] args) {
        System.out.println("Running Main");
        A rv1=new A();
        A rv2=new A();
        System.out.println("The main ends");
    }
}

Every Java class should have a constructor, and if you don’t add a constructor for a class, then Java gives a default constructor for that class.

Types of Constructors

  • Default Constructor

  • Parameterized Constructor

Default Constructor

The Constructor, which is developed by the compiler at the compile time, is automatically called as the default constructor.

public class className {
	className(){
	
	}
}

Parameterized Constructor

The constructor, which is created by the programmer with parameters similar to the methods we created with parameters, is known as the parameterized constructor.

Note: When we created the parameterized constructor, we also needed to create the default constructor on our own as well.

Syntax:

public class className {
  className(){
	
  }
}

// with params
public class className {
  className(int a){
	
  }
}

Difference b/w method & constructor

Method

Constructor

Methods can have any name, they can also have the class name

The constructor name should be similar to the class name

Methods should have a return type, at least void

It should never have a return type, even void

Methods can be static or non-static

It should always be non-static

Methods are not provided by default in Java

It should be a default provided by the Java

Methods may or may not have a return value

It never should have the return value

Constructor Overloading

Constructor overloading is the concept of creating multiple constructors within a class, with different variations, for example, the data type or position of the arguments.

Therefore, with the help of the constructor overloading, we can achieve the constructor chaining and we can get the different ways of creating the objects.

Example:

package oops;

public class MasterBackend {
    public MasterBackend() {
        System.out.println("Master Backend");
    }
    public MasterBackend(int a) {
        System.out.println("Master Backend "+a);
    }
    public MasterBackend(int a, int b) {
        System.out.println("Master Backend "+a+b);
    } 
    public MasterBackend(int a, int b, int c) {
        System.out.println("Master Backend "+a+b+c);
    }
}

In the example above, when we call the constructor with the new keyword, then all the constructors of the class are called depending on the number of arguments we pass during initialization.

new Keyword is used to call the constructor

public static void main(String[] args) {
        MasterBackend masterBackend1 = new MasterBackend();
        MasterBackend masterBackend2 = new MasterBackend(10,20,30);
        MasterBackend masterBackend3 = new MasterBackend(10,20);
        MasterBackend masterBackend4 = new MasterBackend(10);
    }

output:

Master Backend
Master Backend 102030
Master Backend 1020
Master Backend 10

Example - Volume of Box and Cubic with constructor

// Box Class
class Box {
    double length, width, height;

    // Constructor for Box
    Box(double length, double width, double height) {
        this.length = length;
        this.width = width;
        this.height = height;
    }

    // Method to calculate volume
    double calculateVolume() {
        return length * width * height;
    }
}

// Cube Class (inherits from Box)
class Cube extends Box {

    // Constructor for Cube (all sides are equal)
    Cube(double side) {
        super(side, side, side); // Using Box constructor
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating Box Object
        Box box = new Box(5.0, 4.0, 3.0);
        System.out.println("Volume of Box: " + box.calculateVolume());

        // Creating Cube Object
        Cube cube = new Cube(4.0);
        System.out.println("Volume of Cube: " + cube.calculateVolume());
    }
}

Output:

Volume of Box: 60.0
Volume of Cube: 64.0

In this code snippet, we used the super() statement for calling the super class constructor. We will discuss more on the super() statement after the this() statement.

Conclusion

Constructors in Java initialize objects and share the class name without a return type. The this() keyword invokes another constructor within the same class, enabling constructor chaining and reducing redundancy.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board