Java Constructors

Java Constructors

Java Constructors

In this tutorial, you’ll find out about Java constructors, how to make and use them, and various types of constructors with the help of examples.

What is Constructor?

In Java, each class has its constructor that is conjured automatically when an object of the class is made. A constructor is like a method however in genuine, it’s not a method.

A Java method and Java constructor can be separated by its name and bring type back. A constructor has a similar name as that of class and it doesn’t restore any worth. For instance,

class Test {
    Test() {
        // constructor body
    }
}

Here, Test() is a constructor. It has the same name as that of the class and doesn’t have a return type.

class Test {
    void Test() {
        // method body
    }
}

Here, Test() has the same name as that of the class. However, it has a return type void. Hence, it’s a method, not a constructor.

Recommended Reading: Why do constructors not return values


Example: Java Constructor

class Main {
   private int x;

   // constructor
   private Main(){
       System.out.println("Constructor Called");
       x = 5;
   }

   public static void main(String[] args){
       // constructor is called while creating object
       Main obj = new Main();
       System.out.println("Value of x = " + obj.x);
   }
}

Output

Constructor Called
Value of x = 5

In the above example, we have a private constructor named Main(). Inside the main method, we are creating an object named obj of the class.

Main obj = new Main();

During this process, the constructor is called. Subsequently, the print explanation is executed and the variable x is introduced.


Types of Constructor

In Java, constructors can be divided into 3 types:

  • No-Arg Constructor
  • Default Constructor
  • Parameterized Constructor

No-Arg Constructor

A Java constructor could conceivably have any parameters (arguments). If a constructor doesn’t accept any parameters, it is known as a no-arg constructor. For instance,

private Constructor() {
   // body of constructor
}

Example of the no-arg constructor

class Main {

   int i;

   // constructor with no parameter
   private Main(){
       i = 5;
       System.out.println("Object created and i = " + i);
   }

   public static void main(String[] args) {

       // calling the constructor without any parameter
       Main obj = new Main();
   }
}

Output

Object created and i = 5

Here, the constructor Main() does not accept any parameters.

Did you notice that the access modifier of the Main() constructor is private?

This is because the object is started up from inside a similar class. Hence, it can get to the constructor.

Be that as it may, if the object was made outside of the class, you need to proclaim the constructor public to access it. For instance:

class Company {
    String domainName;

    // public constructor
    public Company(){
        domainName = "worldofitech.com";
    }
}

public class Main {
    
    public static void main(String[] args) {

    // object is created in another class
        Company companyObj = new Company();
        System.out.println("Domain name = "+ companyObj.domainName);
    }
}

Output

Domain name = worldofitech.com

Default Constructor

If you don’t make any constructors, the Java compiler will consequently make a no-contention constructor during run-time. This constructor is known as the default constructor. The default constructor instates any uninitialized case variables with default values.

TypeDefault Value
booleanfalse
byte0
short0
int0
long0L
char\u0000
float0.0f
double0.0d
objectReference null

Example: Default Constructor

class DefaultConstructor {

    int a;
    boolean b;

    public static void main(String[] args) {

        // A default constructor is called
        DefaultConstructor obj = new DefaultConstructor();

        System.out.println("a = " + obj.a);
        System.out.println("b = " + obj.b);
    }
}

Output

a = 0
b = false

In the above program, we have not instated the value of both the variables, an and b. However, when we make an object of the class, we can find in the Output that the values are instated with certain qualities.

It is because the Java compiler has automatically created a default constructor. The constructor will initialize the value of variables a and b with default values 0 and false

The above program is equivalent to:

class DefaultConstructor {

    int a;
    boolean b;

    // a private constructor 
    private DefaultConstructor() {
        a = 0;
        b = false;
    }

    public static void main(String[] args) {
        // call the constructor 
        DefaultConstructor obj = new DefaultConstructor();

        System.out.println("a = " + obj.a);
        System.out.println("b = " + obj.b);
    }
}

Output

a = 0
b = false

Parameterized Constructor

Similar to methods, we can pass parameters to a constructor. Such constructors are known as a parameterized constructor. For instance,

private Constructor (arg1, arg2, ..., argn) {
    // constructor body
}

Example: Parameterized constructor

class Vehicle {

    int wheels;

    // constructor accepting single value
    private Vehicle(int wheels){
        this.wheels = wheels;
        System.out.println(wheels + " wheeler vehicle created.");
    }

    public static void main(String[] args) {

        // calling the constructor by passing single value
        Vehicle v1 = new Vehicle(2);
        Vehicle v2 = new Vehicle(3);
        Vehicle v3 = new Vehicle(4);
    }
}

Output

2 wheeler vehicle created.
3 wheeler vehicle created.
4 wheeler vehicle created.

In the above example, we have a constructor named Vehicle(). The constructor accepts a single parameter named wheels.

Here, while making objects, we are passing arguments to the constructor. And, based on the argument, it is generating the output.


Constructors Overloading in Java

Similar to method overloading, we can also overload constructors in Java. If you are not familiar with method overloading, visit Java Method Overloading.

In constructor overloading, there are two or more constructors with different parameters. For example,

class Company {

    String domainName;

    // constructor with no parameter
    public Company(){
        this.domainName = "default";
    }

    // constructor with single parameter
    public Company(String domainName){
        this.domainName = domainName;
    }

    public void getName(){
        System.out.println(this.domainName);
    }

    public static void main(String[] args) {
        // calling the constructor with no parameter
        Company defaultObj = new Company();

        // calling the constructor with single parameter
        Company worldofitechObj = new Company("worldofitech.com");

        defaultObj.getName();
        worldofitechObj.getName();
    }
}

Output

default
worldofitech.com

In the above example, we have two constructors: public Company() and public Company(String domainName).

Here, both the constructor are introducing the variable domainName with various qualities. Subsequently, in light of the worth we need, we can call the constructor from the main() method.


Important Notes

Constructors are conjured certainly when you start up objects.

The two standards for making a constructor are:

The name of the constructor ought to be equivalent to that of class.

A Java constructor must not have a bring type back.

If a class doesn’t have a constructor, the Java compiler naturally makes a default constructor during run-time. The default constructor instates occasion factors with default esteems. For instance, the int variable will be introduced to 0

Constructor types:

No-Arg Constructor – a constructor that doesn’t accept any arguments

Default Constructor – a constructor that is automatically made by the Java compiler if it isn’t expressly characterized.

Parameterized constructor – a constructor that accepts arguments

A constructor can’t be abstract or static or last.

A constructor can be over-burden yet can not be overridden..


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

Leave a Reply

Your email address will not be published. Required fields are marked *