Constructors in Java

Constructors in Java

In this article, I am going to discuss Constructors in Java with examples. Please read our previous article, where we discussed Class and Objects in Java. At the end of this article, you will understand what are Constructors and its type as well as its role and responsibility in Java Applications with Examples.

What are Constructors in Java?

Java allows the object to initialize itself when it created. This automatic initialization is known as Constructors. The constructor is a block of code that initializes the newly created object.

A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is called automatically immediately after the object is created, before the new operator completes it. Constructors have no return type, not even void.

Defining a Constructor in Java:

This a simple Java Constructor Declaration example:

What are Constructors in Java?

How does Constructor work in Java?

Let’s say we have a class MyClass in the above declaration. When we create the object of MyClass like this:

Myclass myclassobj = new Myclass();

The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object. Each time an object is created using new keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

Why do we need a Constructor?

Constructors initialize the new object, that is, they set the startup property values for the object. They might also do other things necessary to make the object usable. You can distinguish constructors from other methods of a class because constructors always have the same name as the class.

Rules for Constructors:
  • The name of the constructor must be the same as that of a class name in which it resides.
  • Constructors must not have a return type. If you keep return type for the constructor, it will be treated as a method.
  • Every class should have at least one constructor. If you don’t write a constructor for your class, the compiler will give default constructor. 
  • A constructor in Java cannot be abstract, final, static, and Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
Types of Constructors in Java:

Basically there are three types of constructors in java:

  1. Parameterized Constructors
  2. Default Constructors
  3. Copy Constructors

Types of Constructors in Java

Parameterized Constructor in Java:

Constructors with parameters that can be used to initialize the internal state (fields) of the newly created object are known as Parameterized Constructors.  If we want to initialize fields of the class with your own values, then use a parameterized constructor.

Sample program for Parameterized Constructor:
package Demo;
import java.io.*; 
class Student
{ 
    // data members of the class. 
    String name; 
    int id; 
  
    // constructor would initialize data members 
    // with the values of passed arguments while 
    // object of that class created. 
    Student(String name, int id) 
    { 
        this.name = name; 
        this.id = id; 
    } 
} 
  
public class ParameterizedConstructor {
 
 public static void main(String args[]) 
        {
             // this would invoke the parameterized constructor. 
             Student student1 = new Student("Ashok", 101); 
             System.out.println("Student Name :" + student1.name + " and Student Id :" + student1.id); 
        }
}

Output:

Parameterized Constructor in Java

Default Constructor in Java:

A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. Therefore, it is also known as a no-args constructor. Once the class is compiled it will always at least have a no-argument constructor. If you do define a constructor for your class, then the Java compiler will not insert the default no-argument constructor into your class.

Sample Program for Default Constructor:
package Demo;

public class DefaultConstructor {
    public DefaultConstructor()
    {
        System.out.println("This is a no argument constructor");
    }
    public static void main(String args[]) {
   	 new DefaultConstructor();
    }
}

Output:

Default Constructor in Java

Copy Constructor in Java:

A copy constructor is used for copying the values of one object to another object.

Sample Program for Copy Constructor:
package Demo;

public class CopyConstructor {
    String web; 
    CopyConstructor(String w){  
  web = w;
    }  

    /* This is the Copy Constructor, it 
     * copies the values of one object
     * to the another object (the object
     * that invokes this constructor)
     */
    CopyConstructor(CopyConstructor cc){  
  web = cc.web; 
    }  
    void disp(){
  System.out.println("Constructor: "+web);
    }  

    public static void main(String args[]){  
  CopyConstructor obj1 = new CopyConstructor("Example of Copy Constructor in Java");  
   
  /* Passing the object as an argument to the constructor
   * This will invoke the copy constructor
   */
  CopyConstructor obj2 = new CopyConstructor(obj1);  
  obj1.disp();  
  obj2.disp();  
    }  
}

Output:

Copy Constructor in Java

Calling a Constructor from another Constructor: this Keyword

In Java, it is possible to call a constructor from inside another constructor. When you call a constructor from inside another constructor, you need to use this keyword to refer to the constructor.

this keyword can be very useful in the handling of Variable Hiding. We cannot create two instances/local variables with the same name. However, it is legal to create one instance variable & one local variable or method parameter with the same name. In this scenario, the local variable will hide the instance variable this is called Variable Hiding.

Sample Program for this Variable for Variable Hiding:
package Demo;

public class VariabeHiding {
 int variable = 5;

 public static void main(String args[]) {
  VariabeHiding obj = new VariabeHiding();

  obj.method(20);
  obj.method();
 }

 void method(int variable) {
  variable = 10;
  System.out.println("Value of Instance variable :" + this.variable);
  System.out.println("Value of Local variable :" + variable);
 }

 void method() {
  int variable = 40;
  System.out.println("Value of Instance variable :" + this.variable);
  System.out.println("Value of Local variable :" + variable);
 }
}

Output:

Calling a Constructor from another Constructor : this Keyword

Calling Constructors in Superclasses by using Super Keyword:

The super keyword refers to superclass objects. It is used to call superclass methods, and to access the superclass constructor. The keyword “super” came into the picture with the concept of Inheritance. Inheritance in detail we will cover in my tutorial of Inheritance in Java.

Note: super keyword can call both parametric and non-parametric constructors.

Sample Program for Super Keyword:
package Demo;

class College { // Superclass (parent)
   public void collegeRecord() {
     System.out.println("The college is good with good placemet record");
   }
}

class Students extends College { // Subclass (child)
   public void collegeRecord() {
     super.collegeRecord(); // Call the superclass method
     System.out.println("The students of this college are performing good in academics.");
   }
}

public class SuperDemo {
   public static void main(String args[]) {
     College myStudent = new College(); // Create a Dog object
     myStudent.collegeRecord(); // Call the method on the Dog object
   }
}

Output:

Calling Constructors in Superclasses by using Super Keyword

Constructor Overloading in Java

More than one constructor with a different signature in a class is called constructor overloading. The signature of the constructor includes the number, type, and sequence of arguments.

If two constructors in the same class have the same signature, it represents an ambiguity. In this case, the Java compiler will generate an error message because the compiler will unable to differentiate which form to use.

Hence, an overloaded constructor must have different signatures. The Java compiler decides which constructor has to be called depending on the number of arguments passing with the object.

Sample Program for Overloaded Constructor:
package Demo;

class Student1
{
    int Roll;
    String Name;
    double Marks;

    Student1(int R,String N,double M)        // Constructor 1
    {
        Roll = R;
        Name = N;
        Marks = M;
    }

    Student1(String N,double M,int R)        // Constructor 2
    {
        Roll = R;
        Name = N;
        Marks = M;
    }

    void Display()
    {
        System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks);
    }
}

class ConstructorOverloading
{
    public static void main(String[] args)
    {
        Student1 S1 = new Student1(1,"Kumar",78.53);  // Statement 2
        Student1 S2 = new Student1("Sumit",89.42,2);  // Statement 1

        System.out.print("\n\tRoll\tName\tMarks\n");
        S1.Display();
        S2.Display();
    }
}

Output:

Constructor Overloading in Java

Some interview questions related to Constructors in Java with Examples:

Can we define a method with the same class name?

Yes, it is allowed to define a method with the same class name. NO compile-time error and NO runtime error are raised but it is not recommended as per coding standard.

If we place return type in the constructor prototype will it lead to CE?

No, because compiler and JVM consider it as a method.

How compiler and JVM differentiate constructor and method definitions if both have the same class name?

By using return type. If there is a return type then it is considered a method else it is considered as a constructor.

How compiler and JVM differentiate constructor and method invocations if both have the same class name?

By using the new keyword. If the new keyword is used in calling then the constructor is executed else method is executed.

Why return type is not allowed in the constructor?

As there is a possibility to define a method with the same class name, the return type is not allowed to the constructor to differentiate constructor block from method block.

Why constructor name should be the same as the class name?

Every class object is created by using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name.

Can we declare constructor as private?

Yes. We can declare constructor as private. All four accessibility modifiers are allowed to the constructor. We should declare constructor as private for not allowing users to create an object from outside of our class. Basically we will declare constructor as private to implement a singleton design pattern.

Is constructor definition is mandatory in a class?

No, it is optional. If we don’t define a constructor then the compiler will define the constructor.

How many types of constructors are there in java?

Java supports three types of constructors

Default constructor: The compiler given constructor is called as default constructor. It does not have parameters and logic except a super() call.

No-argument/non-parameterized constructor: The developer given constructor without parameter is called as no-argument or non-parameterized constructor.

Parameterized constructor: The developer given constructor with parameters is called as parameterized constructor.

Rule: super() call must also be placed as the first statement in the developer given constructor. If the developer does not place it, compiler place this statement.

Why compiler given constructor is called as default constructor?

Because it obtains all its default properties from its class

  1. Its accessibility modifier is the same as its class accessibility modifier.
  2. Its name is the same as its class name.
  3. It does not have parameters and logic
What is the default accessibility modifier of a default constructor?
  • It is assigned from its class. So it may be default or public.
  • If a class is created with a default accessibility modifier then the constructor is also created with default accessibility modifier.
  • If the class is created with public accessibility modifier then the constructor is also created with public accessibility modifier.
Why compiler defines the default constructor without logic and parameters?
  • Because the compiler does not know the logic required for our class. The object’s initialization logic is different from one class to another class.
  • But it place super() method call in all constructors because it is generic logic required for every class for calling superclass constructor in order to initialize superclass non-static variables when subclass object is created.
  • Since there is no logic in default constructor compiler defines the default constructor without parameters.
When does the compiler provide the default constructor?

Only if there is no explicit constructor defined by the developer.

When the developer must provide the constructor explicitly?

If we want to execute some logic at the time of object creation, that logic may be object initialization logic or some other useful logic, then the developer must provide the constructor explicitly.

If the class has an explicit constructor, does it has a default constructor?

No, the compiler places default constructor only if there is no explicit developer given constructor.

How can we create an object of a class?

We must create an object of a class by using the new keyword and available constructor.

Can we consider both default and no-argument constructors are the same?

No, both are different. They seem to be the same but not really the same.

What are the differences between no-argument and default constructor?

What are the differences between no-argument and default constructor? .

Note: The common point between these two constructors is both constructors don’t have parameters.

Can we define a class with public accessibility modifier and a constructor with other accessibility modifiers?

Yes, we can define it. The compiler does not change the developer given constructor’s accessibility modifier to class accessibility modifier.

When should we define a parameterized constructor in a class?

To initialize objects dynamically with the user given values then we should define the parameterized constructor.

How many constructors can be defined in a class?

In a class, we can define multiple constructors but every constructor must have different parameters type and parameter order. So in a class, we can define one no-argument constructor plus ‘n’ number of parameterized constructors.

What is constructor overloading?

Defining multiple constructors with different parameter types/order/ list is called as constructor overloading.

In an object creation apart from invoked constructor do other constructors are also executed?

No, only the invoked constructor is executed. Other constructors will not be executed.

Then how can we execute logic when an object is created using any of the constructors?

Solution1: Write that logic in all constructors.

Problem: It is not recommended because we lose code re-usability and centralized code change. Since code is redundant we must perform code change in every constructor, it leads to a lot of maintenance costs because after code change every constructor’s logic should check again.

Solution2: As per modularity write that logic in a non-static method and call that method in all constructors.

Problem: It is also not recommended because there is a chance of missing calling that method in one of the constructors and also that method can be called after object creation.

Solution3: The best solution for this requirement is Non-Static Block (NSB)

Difference Between Methods and Constructors in Java
Constructors Methods
It is a special type of method used to initialize objects of its class. Methods are set of instructions that are invoked at any point in a program to return a result.
The purpose of a constructor is to create an instance of a class. The purpose of a method is to execute a Java code.
They are called implicitly immediately after object creation. They are called directly without even creating an instance of that class.
They are used to initialize objects that don’t exist. They perform operations on already created objects.
The name of the constructor must be the same as the name of the class. They can have arbitrary names in Java.
They are not inherited by subclasses.

They are inherited by subclasses.

In the next article, I am going to discuss Inner Classes in Java and its type with examples. Here, in this article, I try to explain the Constructors in Java with examples and I hope you enjoy this Constructors in Java with examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Constructors in Java with examples article.

Leave a Reply

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