Java – Constructors

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

Syntax

Following is the syntax of a constructor −

class ClassName {
   ClassName() {
   }
}

Java allows two types of constructors namely −

  • No argument Constructors
  • Parameterized Constructors

No argument Constructors

As the name specifies the no argument constructors of Java does not accept any parameters instead, using these constructors the instance variables of a method will be initialized with fixed values for all objects.

Example

Public class MyClass {
   Int num;
   MyClass() {
      num = 100;
   }
}

You would call constructor to initialize objects as follows

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass();
      MyClass t2 = new MyClass();
      System.out.println(t1.num + " " + t2.num);
   }
}

This would produce the following result

100 100

Parameterized Constructors

Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor’s name.

Example

Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
   int x;
   
   // Following is the constructor
   MyClass(int i ) {
      x = i;
   }
}

You would call constructor to initialize objects as follows −

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass( 10 );
      MyClass t2 = new MyClass( 20 );
      System.out.println(t1.x + " " + t2.x);
   }
}

This would produce the following result −

10 20

Lessons

Q 1: What is a Constructor?

Ans: Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.

Q 2: Do we have Copy Constructor in Java?

Ans: Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own. To copy the values of one object into another in java, you can use: Constructor Assigning the values of one object into another clone() method of Object class

Q 3: Difference between instance variable and a class variable.What is Constructor Chaining ?

Ans: Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor. // Java program to illustrate Constructor Chaining // within same class Using this() keyword class Temp { // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println("The Default constructor"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); } }

Q 4: Can we call sub class constructor from super class constructor?

Ans: No. There is no way in java to call sub class constructor from a super class constructor.

Q 5: What happens if you keep a return type for a constructor?

Ans: Ideally, Constructor must not have a return type. By definition, if a method has a return type, it’s not a constructor.(JLS8.8 Declaration) It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.

Q 6: What is No-arg constructor?

Ans: Constructor without arguments is called no-arg constructor. Default constructor in java is always a no-arg constructor.

Q 7: How a no – argument constructor is different from default Constructor?

Ans: If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared. If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

Q 8: Do we have destructors in Java?

Ans: No, Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

Q 9: When do we need Constructor Overloading?

Ans: Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed. According to the situation , a constructor is called with specific number of parameters among overloaded constructors.

Q 10: What are private constructors and where are they used?

Ans: Like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class. The major scenarios where we use private constructor: Internal Constructor chaining Singleton class design pattern