August 22, 2022

Constructor in Java

Constructor in Java is a special method which is called automatically to initialize an object when the object is created.

Need for a constructor

When an object is created it is a very common requirement to initialize that object (provide values for its instance variables). To facilitate that a constructor is provided and Java automatically calls that constructor when an object is created to guarantee initialization.

Java constructor example

public class ConstructorDemo {
  int num;
  String name;
  public ConstructorDemo(int num, String name){
    this.num = num;
    this.name = name;
  }

  public static void main(String[] args) {
    ConstructorDemo cd = new ConstructorDemo(10, "Rodrigo");
    System.out.println("Number is " + cd.num + " Name is " + cd.name);
  }
}
Output
Number is 10 Name is Rodrigo

In the above code constructor is defined as follows, which is a parameterized constructor (constructor with arguments).

public ConstructorDemo(int num, String name){
  this.num = num;
  this.name = name;
}

When an object of the class is created using the new() operator, constructor is called automatically to initialize the object before the object creation is completed by the new operator.

Rules for Constructors

Since constructor in Java is a special method so its usage is governed by special rules which are as follows.

  1. Constructor has the same name as the class that way Java can identify a constructor and call it automatically.
  2. Constructor doesn’t have a return type not even void. That’s what differentiates a constructor from a regular method. If a return type is specified then it is not treated as a constructor but a regular method.
  3. A constructor in Java can have a public, protected, default (package-private) or private access modifier.
  4. A constructor in Java can’t be final. Trying to make a constructor final results in compile time error “Illegal modifier for the constructor in type; only public, protected & private are permitted

Types of constructors

Constructor in Java can be of two types-

  • No-arg constructor- A constructor with no parameters. A default no-arg constructor is implicitly inserted by the Java itself if you don’t provide a constructor in your class.
  • Parameterized constructor- A constructor with parameters. If you explicitly specify a constructor in your class then the default no-arg constructor is not inserted implicitly.
No-arg constructor example
public class ConstructorDemo {
  public static void main(String[] args) {
    ConstructorDemo cd = new ConstructorDemo();
  }
}

Here when the object is created ConstrucorDemo cd = new ConstrucorDemo(); the default no-arg constructor is called.

Parameterized Constructor
public class ConstructorDemo {
  int num;
  String name;
  public ConstructorDemo(int num, String name){
    this.num = num;
    this.name = name;
  }

  public static void main(String[] args) {
    ConstructorDemo cd = new ConstructorDemo(10, "Rodrigo");
    System.out.println("Number is " + cd.num + " Name is " + cd.name);
    
    //This will call no-arg constructor - ERROR
    ConstructorDemo cd1 = new ConstructorDemo();
  }
}

This code will result in compile time error - “The constructor ConstrucorDemo() is undefined”. Since a parameterized constructor is already provided so default no-arg constructor is not provided in this case.

If you want no-arg constructor also in this case then you will have to explicitly write it. You can have more than one constructor in the same class that is known as constructor overloading in Java.

public class ConstructorDemo {
  int num;
  String name;
  // Parameterized constructor
  public ConstructorDemo(int num, String name){
    this.num = num;
    this.name = name;
  }
  // no-arg constructor	
  public ConstructorDemo(){
    
  }
	
  public static void main(String[] args) {
    ConstructorDemo cd = new ConstructorDemo(10, "Rodrigo");
    System.out.println("Number is " + cd.num + " Name is " + cd.name);
    
    //This will call no-arg constructor
    ConstructorDemo cd1 = new ConstructorDemo();
  }
}

Private constructor in Java

A constructor in the class can have private access modifier too, in that case constructor will only be visible with in the class it is created so no other class would be able to create instance of the class. That helps in controlling the instantiation of the class. One class design where you can see use of private constructor is Singleton design pattern where you control the instantiation of the class so that there is only one instance of the class.

Private constructor example in Java

public class ConstructorDemo {
  int num;
  String name;
  // Parameterized constructor
  private ConstructorDemo(int num, String name){
    this.num = num;
    this.name = name;
  }

  public static void main(String[] args) {
    ConstructorDemo cd = new ConstructorDemo(10, "Rodrigo");
    System.out.println("Number is " + cd.num + " Name is " + cd.name);
  }
}

When object is created in the same class- ConstructorDemo cd = new ConstructorDemo(10, "Rodrigo"); that is OK.

But trying to create object of ConstructorDemo class from any other class results in an error “The constructor ConstructorDemo(int, String) is not visible”.

That's all for the topic Constructor in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment