Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Back to home
Logicmojo - Updated Jan 11, 2023



When programming, it may occasionally be required to initialise the data members and member functions of the objects before performing any operations. The variables that are defined in any class using either derived data types or fundamental data types (such int, char, float, etc.) are referred to as data members (like class, structure, pointer, etc.). The functions that are defined within a class declaration are known as member functions.

Imagine you are developing a video game. Every time a new player registers, we need to provide a default value for the game's initial position, health, acceleration, and a few other variables.
To do this, it is possible to define distinct functions for each quantity and then assign the required default values to each quantity. We have to call a series of routines each time a new player registers to do this. This process may now become difficult and drawn out.
What if the amounts were automatically assigned when the new player made their declaration? A constructor makes this easier and more efficient to do.

What is Constructor in Java

The constructor is called and the resulting object of the class are both returned whenever we use the new keyword to create an instance of a class. Since the constructor can only return an object to the class, the Java runtime performs this function implicitly, and we are not supposed to modify it by adding a return type. A constructor will change into a class method if we include a return type in it. This is how a constructor and a regular method are distinguished by the Java runtime.

public Person() {
	System.out.println("Person Constructor");
}


public Person Person() {
	System.out.println("Person Method");
	return new Person();
}

First one is a constructor in this case; take note that neither a return type nor a return statement are there. In the second, which is a regular method, we once more call the first constructor to obtain an instance of Person and return it. It is advised against having the method name and class name be the same because this causes confusion.

Making of Constructors in Java

Constructors are far more complicated than simply being declared in a class. For instance, a constructor can act on the creation of a new object in order to fulfil the requirements of the class to which it belongs. Consider a use case, then utilise it to construct an example.
KingLords are the kind of character you determine you'll need to make for the plot when making a video game. They will have a name and an age, two characteristics. Consequently, you design a class that has two variables and a constructor that gives each variable a value upon object creation. The code needed to generate the constructor with parameters is displayed in the following code snippet, which clarifies this procedure.

class KingLord{
   String name;
   int age;

    KingLord(String name, int age) {
      this.name = name;
      this.age = age;
   }
}

Need of Constructor

Data members are automatically allocated beneath each object you create when you use a class to create multiple objects. The data members corresponding to each object will have the identical initial values if initialising data members at the time of class declaration is permitted. In reality, though, you would prefer to have distinct starting values for the instance variables of the objects, and if you use any member methods to initialise the data members, you might need to call them individually after creating each object. The concept of constructors was thus a gift from the developers of Java. In order to initialise an object, you therefore need a member method that can be called automatically while generating an object.

As a result, while creating an object, constructors are used to assign values to the class variables. This is done either manually by the developer or programmer, or via Java's built-in default constructor.

Characteristics of Constructor in Java

Java constructor characteristics include:

      ⮞ The class name and the constructor name are identical. Explanation: Constructors are distinguished from other member functions of the class by the compiler using this character.

      ⮞ A constructor cannot have any sort of return. Nothing at all. It automatically calls and is frequently employed for initialising values, as explained.

      ⮞ When an object is created for the class, the constructor is automatically called.

      ⮞ Contrary to C++ constructors, Java prohibits the definition of a constructor outside of a class.

      ⮞ Typically, constructors are used to initialise all of the class's data members (variables).

Types of Constructor

Default Constructor

If no constructor is explicitly stated in the class, a default constructor is automatically built when an object is created. This kind of constructor automatically creates without being defined and declared in the class; it is not visible in the application.

class rec_shape
{
    double len = 10;
    double br = 30;
 
    double Areafind()
    {return len*br;}
}
 
class rec_shape_Main {
    public static void main(String[] args) {
        double area;
        rec_shape myrec = new rec_shape();
        area = myrec.Areafind();
        System.out.println("The area of the rec_shape: " +area); 
    }
}

No-argument Constructor

Contrary to default constructors, no-argument constructors are accessible in the class. Additionally, a constructor definition with no arguments is present (or parameters). When a class object is created, they are called. These constructors typically have variables defined for other member functions.

class shape_rec
{
    double len;
    double br;
 
    shape_rec()
    {
        len = 15.5;
        br = 10.67;
    }
    double Areafind()
    {return len*br;}
}
 
class shape_rec_Main {
    public static void main(String[] args) {
        double area;
        shape_rec myrec = new shape_rec();
        area = myrec.Areafind();
        System.out.println("The area of the shape_rec: " +area); 
    }
}

Parameterized Constructor

It has parameters (or arguments) in the constructor definition and declaration, in contrast to No-argument constructor. Ja va's parameterized constructors support passing multiple arguments.

These kinds of constructors are additionally typically employed in constructor overloading to distinguish between several constructors with various datatypes.

class shape_rec
{
    double len;
    double br;
 
    shape_rec()
    {
        len = 10;
        br = 20;
    }
 
    shape_rec(double l, double b)
    {
       len = l;
       br = b;
    }
 
    double Areafind()
    {return len*br;}
}
 
class shape_rec_Main {
    public static void main(String[] args) {
        double area;
        shape_rec myrec = new shape_rec(41,56);
        area = myrec.Areafind();
        System.out.println("The area of shape_rec: " +area); 
    }
}

Copy Constructor

Copy constructors are supported by Java, and they specify what the compiler does when copying class objects. Java does not, however, produce a default copy constructor. It only has one formal parameter, the type of the class, which is used to duplicate an existing object of the same class (the parameter may be a reference to an object). It counts as a conversion constructor even though both classes are the same. The class constructors used in.NET that share the same shorthand as the copy constructors we use in Java, copy ctor or cctor, are unrelated.

Direct entry copy constructor:

class copy_constructor { 
    int a,b; 
    copy_constructor(int x,int y) { 
        a=x ; 
        b=y ; 
        
    } 
} 
class abc { 
    public static void main(String[] args) { 
        copy_constructor ob=new copy_constructor(5,8); 
        copy_constructor ob1=ob; 
        
    } 
} 

Copy constructor by passing object

The object is given to the constructor in this system. Additionally, the values from the objects supplied to the constructor are copied into the instance variables of the current object, or the object through which the constructor is called.

class copy_constructor { 
    int a,b; 
    copy_constructor(int x,int y) { 
        a=x ; 
        b=y ; 
        
    } 
    copy_constructor(copy_constructor p) { 
        a=p.a ; 
        b=p.b ; 
        
    } 
} 
class abc { 
    public static void main(String args[]) 
    { 
        copy_constructor ob=new copy_constructor(5,8); 
        copy_constructor ob1=new copy_constructor(ob); 
        
    } 
} 

How do Java constructors and methods differ from one another?

While it is not required for Java methods, constructors must and should have the same name as the class in which they are declared.
While methods have a return type or void if they don't return any values, constructors don't return any return types.
While method(s) can be called as many times as necessary, the constructor is only ever called once when an object is created.

Construction Overloading

Constructors can be overloaded to generate objects in many ways, just like method overloading. The number of arguments a constructor accepts, along with other factors like the arguments' passing order, are used by the compiler to distinguish various constructors.

class Logicmojo {
    string name, course, technology;
    Logicmojo(string s , string n){
        name = s ;
        course = n ;
        
    }
    Logicmojo(string s , string n , string c){
    name = s;
    course = n;
    technology = c;
    }
    void show( ) 
    { System.out.println(name +""+course+""+technology); }
 
    public static void main(String args[ ])
    {
         Logicmojo ob1 = new Logicmojo("Logicmojo" , "Java") ;
         Logicmojo ob2 = new Logicmojo("Logicmojo" , "J2EE" , "Java");
         ob1.show( );
         ob2.show( );
    }
}

Super Constructor for Java

When a class must call the constructor of a superclass because it has been inherited, we can do so by using the super keyword. Let's look at an illustration of how to use the super class constructor. Keep in mind that the child class constructor should begin with a call to the super constructor. Java also initialises the super class before the child class when instantiating a child class constructor. Therefore, Java runtime calls the default or no-args constructor if the super class constructor is not explicitly called. Let's use a programme example to better comprehend these topics. Consider that we have two classes, as shown below.

public class Man {

	private int age;

	public Man() {
		System.out.println("Man Created");
	}

	public Man(int i) {
		this.age = i;
		System.out.println("Man Created with Age = " + i);
	}

}

public class candidate extends Man {

	private String name;

	public candidate() {
		System.out.println("candidate Created");
	}

	public candidate(int i, String n) {
		super(i); // super class constructor called
		this.name = n;
		System.out.println("candidate Created with name = " + n);
	}

}


Learn More

Java Constructor Guidelines

The constructor's name should correspond to the class name.
It is not possible to specify a constructor to be final, static, synchronised, or abstract.
It cannot specify a return type explicitly.
An access modifier may be present in a constructor to regulate access.

Constructor Chaining

Calling one constructor from another with respect to the current object is known as constructor chaining.
By using constructor overloading, constructor chaining is primarily used to reduce code duplication and improve readability when there are several constructors.
Through inheritance, constructor chaining takes place. The function of a subclass constructor is to first invoke the constructor of the superclass. This makes sure that the superclass's data members are initialised before creating an object for a subclass. Any number of classes could be included in the inheritance chain. Up the chain each constructor calls until the top class is reached.

class Foobar {
	
	Foobar()
	{
		System.out.println("default");
	}
	Foobar(int x)
	{
		this();
		System.out.println(x);
	}

	Foobar(int x, int y)
	{
		this(5);
		System.out.println(x * y);
	}

	public static void main(String args[])
	{
		new Foobar(8, 10);
	}
}

Rules for Chaining

Chaining constructor rules:
The constructor's first line must always contain the this() statement.
At least one constructor should not contain the this() keyword.
Any order can be used to produce constructor chaining.

Why is constructor chaining necessary?

This method is used to do numerous jobs in a single constructor rather than writing separate pieces of code for each duty in a single constructor, which improves readability of the programme.

Can we allow private constructors in java?

As you may anticipate, we can give the constructor access specifiers just as with any other method. If it is set to private, only members of the class can access it.

Do we actually need these "private constructors"?

We can utilise private constructors in a variety of situations. The principal ones are

Internal Constructor chaining
Singleton class design pattern

What is Singleton class?

A class is referred to as singleton, as the name suggests, if it permits only one instance of that class's objects.Such classes can only contain a single object.
Database connectivity and networking ideas both make considerable use of singleton classes.

Why Constructors are not inherited in Java?

A constructor is a section of code with the same name as the class that allows you to create objects of that class without specifying a return type.

When a class (child class) extends another class (parent class), the subclass inherits state and behaviour from the superclass in the form of variables and methods, but it does not inherit constructor of superclass for the following reasons:

Constructors are unique and share the same name as the class. Therefore, if constructors were inherited in child classes, the child class would have a constructor from the parent class, which goes against the requirement that the constructor's name match the class name.

If we define the constructor of the parent class inside the child class, the compiler will complain about the return type and treat the definition as a method. However, the print method is regarded as an overriding method because it does not produce any compile-time errors.

Imagine that constructors could be passed down, in which case encapsulation would be impossible. because we can access and initialise a class's private members by utilising the constructor of a super class.

It is not possible to call a constructor as a method. It is called when a class object is created, hence it makes no sense to build a child class object using the constructor syntax of the parent class. Child c = new Parent(), for example.

Super() is automatically added to the child class constructor if super or this is not explicitly called because a parent class constructor is not inherited in a child class.

Difference Between Constructors and Destructors

ConstructorsDestructors
The compiler calls the constructor to initialise a class object.When the instance is destroyed, the destructor is called.
Constructors are able to accept parameters.No parameters can be passed to the destructor.
The constructor is used to initialise a class object and assign values to the class-specific data members.While a class object's destructor is used to deallocate its memory.
The same class may have more than one constructor.There is only ever one destructor in a class.
Overloaded constructors are possible.You can't overload a destructor.


Difference Between Constructors and Methods

ConstructorsMethod
The name should be same as the class nameName need not to be the same as class name
It has no return type.It has return type.
It is called when we initalise the objects.We can call it as much we want


Conclusions

This concludes our discussion of "Constructor in Java." I sincerely hope that you learned something from it and that it improved your knowledge. You can consult the Java Tutorial if you want to learn more about Java.



Good luck and happy learning!







Frequently Asked Questions (FAQs)



A constructor in Java is a special method that is used to initialize objects of a class. It is called automatically when an object is created and is responsible for setting initial values to the instance variables of the object. Constructors have the same name as the class and do not have a return type, not even void.

Important information:

• A constructor is called automatically when an object is created.

• Constructors have the same name as the class.

• Constructors do not have a return type.



Java needs a constructor for various reasons:

• Constructors initialize objects.

• Constructors allow code reuse

• Private or protected constructors let us control how and where class objects are produced.

• Overloaded constructors let us create things in diverse ways.

• Some objects require sophisticated setup every time they are produced.



The purpose of a constructor is to initialize the state of an object. It is used to set initial values to the instance variables of the object and perform any necessary setup operations. Constructors ensure that an object is in a valid state before it can be used.

Important information:

• Constructors initialize the state of an object.

• They set initial values to instance variables.

• Constructors ensure that an object is in a valid state.



There are two types of constructors in Java: default constructors and parameterized constructors. A default constructor is automatically provided by Java if no constructor is explicitly defined in a class. It initializes the instance variables with their default values. On the other hand, a parameterized constructor is defined with one or more parameters and allows you to pass values to initialize the instance variables.

Important information:

• Default constructors are automatically provided if no constructor is defined.

• Parameterized constructors accept one or more parameters for initialization.

• Default constructors initialize instance variables with their default values.



Yes, a constructor can have parameters. These constructors are called parameterized constructors. By defining parameters in the constructor, you can pass values during the object creation process, allowing for customized initialization of instance variables.

Important information:

• Constructors can have parameters.

• Parameterized constructors allow customized initialization.

• Parameters can be used to pass values during object creation.



Constructor overloading in Java is achieved by defining multiple constructors with different parameter lists in the same class. Each constructor can have a different number of parameters or different types of parameters. When creating an object, the appropriate constructor is selected based on the arguments passed during the object creation.

Important information:

• Constructor overloading is achieved by defining multiple constructors.

• Constructors can have different parameter lists.

• The appropriate constructor is selected based on the arguments passed.



In Java, a class can indeed have many constructors. Overloading of constructors is what this is called. A class can have many constructors with various argument lists thanks to constructor overloading. Each constructor can accept a different set of arguments or initialize the object in a different method.



Having a default constructor in Java is important because it allows the creation of objects without passing any arguments. It provides a fallback option when no specific initialization is required for the instance variables. Additionally, some frameworks and libraries rely on the presence of a default constructor for object instantiation and configuration.



The "this" keyword can be used by a constructor to call another constructor from the same class. Chaining constructors is what is meant by this. To prevent code duplication and carry out typical initialization duties, constructor chaining allows one constructor to call another constructor. The other constructor in the same class is referred to using the "this" keyword.



Constructors in Java cannot be inherited because they are not members of a class. Inheritance only applies to class members such as fields and methods. Each class must define its own constructors to initialize its own members. However, a subclass can call the superclass's constructor using the "super" keyword to initialize the inherited members.

Important information:

• Constructors cannot be inherited in Java.

• Inheritance applies to class members, not constructors.

• Each class must define its own constructors.



In Java, a constructor can indeed be private or protected. A constructor can only be accessed from inside the same class when it is designated private. Design patterns for singletons frequently employ this. When a constructor is marked as protected, it can only be accessed by subclasses of the class or within the same package. Within a class hierarchy, protected constructors are used to offer limited access.



Java automatically provides a default constructor if a constructor is not declared in a class. The instance variables are initialized with their default values (e.g., 0 for numeric types, null for objects) by the default constructor, which accepts no arguments. The default constructor is not automatically provided, though, if any constructors are expressly defined in a class.



Constructors in Java are typically declared as public to allow other classes to create objects of the class. If a constructor is declared with a different access modifier, such as private or protected, it restricts the creation of objects outside the class or its subclasses. Public constructors enable the principle of encapsulation, where objects can be created and used by other parts of the program.



In Java, a copy constructor is a constructor that takes as an argument an object of the same class and copies the data into the new object. Unlike C++, Java doesn't come with a built-in copy constructor, but you can create one yourself.



No, Java does not allow for constructor overriding. Each class's constructors are unique, and constructors are not inherited.


Logicmojo Learning Library