top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Constructor in Java

Introduction

Java is one of the most popular programming languages in the industry and has only grown in popularity since its inception 25 years ago in 1991 by James Gosling of Sun Microsystems Inc.

The use of constructors in Java is a key functionality the programming language provides. 

Constructors are used widely in many programs. They can be customized according to the program's needs and are useful in many situations.

Overview

Constructors are one of the fundamental concepts in Java. In this article, we will learn about constructors in Java, their types, and their use cases. It is a relatively easy and basic topic and strands at the foundation of Java. We will learn about it through various examples.

What are constructors in Java?

Constructor is a special type of method with the same name as the class. It is a member function that initializes an object while creating it in runtime. Like the method, a constructor is a block of codes called when creating an instance of the class. A constructor can be customized per the programs and the required parameters.

What are the rules for creating constructors in Java?

Like every programming language, Java has a set of rules or syntaxes that must be followed. Let us look at the rules to keep in mind for creating a constructor in Java.

  • The name of the constructor and the class should be the same.

  • A constructor cannot be static, synchronized, abstract, or final. 

  • Constructors in Java do not have a return type.

  • In case the programmer has not initialized a constructor, the compiler will make a default one with default values for the needed parameters. 

How are Java constructors different from Java methods?

Java constructors are also referred to as special methods to initialize an object. Although constructors are a type of method, they have some differences. 

The following table elucidates the differences between Java constructors and methods.

Java Constructors

Java Methods

Must have the same name as the class.

Methods can have any name.

Constructors are invoked implicitly by the system.

The programmer invokes methods.

A sub-class cannot inherit constructors.

A sub-class can inherit methods.

Constructors do not have a return type.

Methods must have a return type.

A constructor is used to initialize an object that does not exist.

A method is used to perform operations on an object that already exists.

The compiler provides a constructor.

The compiler never provides a method.

Need of constructors in Java

A constructor in Java is used to create an instance of the class. They share the same name as the class and are very similar to methods. Constructors are also used to request dependencies from the user. A constructor can be configured per the program's needs by passing relevant parameters. They are also used for creating different instances of the same object for different use cases, as program logic demands. 

When constructor is called?

A constructor is called while initializing an object during runtime. If the programmer does not mention a constructor, the compiler issues a default constructor at runtime with no arguments passed. If the compiler sets the default constructor, you have no control over the initial values of the parameters.

Types of Constructors in Java

There are three types of constructors in Java, namely default, parameterized, and no-argument constructors. Here we will discuss them in detail with appropriate examples.

i) Default Constructors

A default constructor in Java is also called an empty constructor and is automatically created by the compiler when we do not create a constructor for the class. A default constructor has no parameter as the name suggests and passes only default values through it. Here is an example of a default constructor.

class Main {
  int value1;
  boolean value2;
  public static void main(String[] args) {
    // A default constructor is called
    Main obj = new Main();
    System.out.println("Default Value:");
    System.out.println("value1 = " + obj.value1);
    System.out.println("value2 = " + obj.value2);
  }
}

As we see from the above example when we do not use a constructor, the compiler initializes the object with default values which in this case are 0 and False for the variables value1 and value2 respectively.

    System.out.println("value1 = " + obj.value1);
    System.out.println("value2 = " + obj.value2);

ii) Parameterized Constructors

The constructors which have a parameter or an argument passed through them are called parameterized constructors in Java. There can be more than one parameterized constructor in a class. Let us understand the concept through an example.

class Main {
  String cars;
  // constructor accepting single value
  Main(String car)
 {
    cars = car;
    System.out.println(cars + " car");
  }
  public static void main(String[] args) {
    // call constructor by passing a single value
    Main obj1 = new Main("mitsubishi");
    Main obj2 = new Main("honda");
    Main obj3 = new Main("suzuki");
  }
}

In the above example, we see that the constructor Main() is parameterized with the value of the car which is then called in the public static void main()

Main(String car)

iii) No-Argument Constructors

A constructor that does not have any argument passed through it is called a no-argument constructor. Let us look at an example to understand it better.

class Student {
  String name;
  // public constructor
  public Student() {
    name = "Rohan";
  }
}
class Main {
  public static void main(String[] args) {
    // object is created in another class
    Student obj = new Student();
    System.out.println(" Student name = " + obj.name);
  }
}

In the above example, we have created a constructor named Student(). As we do not pass any argument or parameter through the Student() constructor, it is called a no-argument constructor.

What is Constructor overloading in Java?

Just like methods, we can also overload constructors in Java. Constructor overloading in Java is used to pass different parameters so that each constructor can perform a different task. Let us understand this concept through an example.

public class Car {  
//instance variables of the class  
int id;  
String name;  
Car(){  
System.out.println("this a default constructor");  
}  
Car(int i, String n){  
id = i;  
name = n;  
}  
public static void main(String[] args) {  
//object creation  
Car s = new Car();  
System.out.println("\nDefault Constructor values: \n");  
System.out.println("Car Id : "+s.id + "\nCar Name : "+s.name);  
System.out.println(" \n Parameterized Constructor values:  \n ");  
Car car = new Car(67842, "Polo");  
System.out.println("Car Id : "+car.id + " \n Car Name : "+car.name);  
}  
}  
In the above example, the Car class is overloaded with two different constructors.
Car(int i, String n)
Car(){

One constructor is parameterized while the other one is the default. We use different constructors to initialize different parameters and values of the class.

We can also see that the Java compiler initializes default values to a constructor when we do not use a constructor. When we initialize a parameterized constructor, we see the default values are overloaded with the values we enter.

How to copy values without constructors in Java?

This simple example lets us understand how to copy values without constructors in Java.

public class Car {
    int id;
    String model;
    // Copy method to copy values from one object to another
    public void copyValues(Car other) {
        this.id = other.id;
        this.model = other.model;
    }
    public static void main(String[] args) {
        Car source = new Car();
        source.id = 10;
        source.model = " Polo ";
        Car destination = new Car();
        destination.copyValues(source);
        System.out.println(" Copied values: ");
        System.out.println("Car Id: " + destination.id);
        System.out.println("Car Model: " + destination.model);
    }
}

In this example, the Car class defines the copyValues method to copy the values from another Car object to the relative current object. The values of id and model are simply assigned from the other object to the desired one.

  public void copyValues(Car other) {
        this.id = other.id;
        this.model = other.model;
    }

We create two Car objects and assign the values to the source object. Then, copyValues() is called on the destination object to copy the information from the source object to the desired place. Finally, the copied values are printed.

Conclusion

Java is one of the most sought-after programming language skills to have in the industry. The use of constructors in Java is a fundamental skill if you are looking to code in Java, which has been thoroughly discussed in this tutorial. If you want to master Java and learn advanced Java concepts, enrolling in a course from upGrad can prove to be of huge help.

FAQs

1. Can constructors be overridden?

Constructors can not be overridden in Java. However, a subclass can provide its own constructors, which can call the superclass constructors using the keyword super(). 

2. What is constructor chaining?

Constructor chaining is a way of calling one constructor from a different constructor relative to the current object. Constructor chaining can be done via two methods

  • From base class using the super keyword.

  • Within the same class by using this() keyword.

3. What is a private constructor?

We can make a private constructor just like a private method using the private keyword. A private constructor can only be used in the same class. 

Leave a Reply

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