Java constructors with example

What is a constructor?
A constructor in java is a special method which has the same name as its class and may or may not receive any arguments. A constructor in java does not return a value unlike a normal method and is preceded with a valid access specifier in java.


Syntax of constructor
As stated above, a constructor has a same name as its class and does not return a value. Thus, syntax to write a constructor in a class is

public class ConstructorDemo {
   /*
   * Constructor
   */
   public ConstructorDemo() {
      System.out.print("Constructor called");
   }
 
}

Notice that the constructor looks similar to a method and its name is the same as that of the class. Also, it does not return a value.
Purpose of constructor
A constructor has following two important uses

  1. It is used for creating an object of a class in java. Whenever an object of a class is created, its constructor is automatically invoked.
  2. A constructor is also used for initializing the values of instance variables of a class. Values may be written inside the constructor itself or may be provided from outside by arguments using a parameterized constructor.


Types of constructor
Constructors may be of following two types.
1. No argument constructor
A constructor which does not accept any arguments is called a no argument or a no-arg constructor. Example is the same as given above.
2. Parameterized constructor
If the constructor accepts one or more than one arguments, then it is called a parameterized constructor. Example,

public class Employee {
 
   private String name;
   private String employeeId;
   /*
   * Parameterized constructor
   */
   public ConstructorDemo(String n, String id) {
      this.name = n;
      this.employeeId = id;
   }
}

A parameterized constructor is used for initializing the values of instance variables of its class supplied from outside as shown above.
Note that the arguments of the constructor are local variables with their scope limited to the body of constructor and they are not visible outside it.
Also, the names of constructor arguments may or may not be identical to the instance variable names.
Constructor example
Till now, we have learnt that a constructor is used for creating objects of a class.
Let us understand it with an example program below.

public class Student {
   private String name;
   private int class;
   private char section;
 
   /*
   * No-arg constructor
   */
   public Student() {
      // initialize instance variable
      this.name = "JK";
   }
 
   /*
   * Parameterized constructor
   */
   public Student(String n, int c, char sec) {
      this.name = n;
      this.class = c;
      this.section = sec;
   }
 
   public static void main(String... args) {
      // create object using no-arg constructor
      Student studentOne = new Student();
      // create object using parameterized constructor
      Student studentTwo = new Student("Abc", 5, 'C');
   }
}

In the above example, when first object is created, then the no argument constructor is invoked and when second object is created, then parameterized constructor is invoked.


Default constructor
Have you ever thought that even if you do not write a constructor in your class, you are still able to create its object using new operator as Employee emp = new Employee();?
This is because if you do not provide a constructor in a class, then it is created by the compiler automatically. It is called default constructor.
It is called default because it is created by the compiler itself. A default constructor will always be a constructor with no arguments or parameters.
One important point to remember is that the compiler will create a default constructor only if no constructor is written in the class. If you create a parameterized constructor in your class, then the default constructor will not be created.
In this case, the statement Employee emp = new Employee(); will be a compiler error since there will be no matching constructor.
Private constructor
As stated earlier, a constructor can be preceded with any of the access specifiers in java. One of those is private. If a constructor is made private, then it will be visible only inside its class, not even child classes.
This means that if the constructor of a class is private, then you will not be able to create its object outside that class, not even in its sub-classes.
A private constructor is mostly used to make a class singleton. A singleton class is one whose one and only one object exists throughout the application.
Constructor overloading
Overloading a constructor means creating more than one constructors in a class having different number or type of arguments or both. It is same as method overloading in java.
An example program of constructor overloading is given below.

public class Student {
   private String name;
   private int class;
   private char section;
   /*
   * Default constructor
   */
   public Student(int class) {
   }
 
   /*
   * Parameterized constructor
   */
   public Student(String sname) {
      this.name = sname;
   }
   /*
   * Parameterized constructor
   */
   public Student(String n, int c, char sec) {
      this.name = n;
      this.class = c;
      this.section = sec;
   }
 
   public static void main(String... args) {
      // create object using constructor
      Student studentOne = new Student(10);
      // create object using parameterized constructor
      Student studentTwo = new Student("Xyz", 7, 'A');
 
      // create object using parameterized constructor
      Student studentTwo = new Student("Abc");
   }
}

Above example contains three constructors each having a different number of arguments. It also creates 3 objects using those constructors.
When creating objects, appropriate constructor depending on the number of arguments is invoked. This is similar to method overloading in java.
Remember that in above case, default constructor will not be created automatically by the compiler.

Constructor modifiers
A constructor can be
private,
protected,
public, or
default(no specifier).
A constructor can not be
static,
synchronized,
final, or
abstract
Abstract class constructor
It is often asked that since you cannot make an object of abstract class, can it have a constructor? It is also a very popular interview question.
The answer is an abstract class can definitely have a constructor. It is used to initialize its instance variables.
Now a second question arises. When you cannot create an object of abstract class, then when is its constructor invoked?
The answer is, An abstract class itself is incomplete, it needs to be sub-classed. When ever an instance of its child class is created, the constructor of abstract class will also be invoked through constructor chaining.
Example,

public abstract class AbstractConstructorDemo {
   // instance variable
   private String message;
 
   public String getMessage() {
      return message;
   }
   /*
   * Abstract class constructor
   */ 
   public AbstractConstructorDemo() {
      System.out.print("Abstract constructor called");
      this.message = "Learning abstract constructor";
   }
}

Above code defines an abstract class with a constructor and a single class field. The constructor is used to initialize the class field value. Now, let’s create its child class.

public class AbstractChild extends AbstractConstructorDemo  {
 
   /*
   * Main method
   */
   public static void main(String... args) {
      // create child class object
      AbstractChild object = new AbstractChild();
      // print instance variable of parent
      System.out.print(object.getMessage());
   }
}

Child class does not contain a constructor which means that the compiler supplies a default constructor. It also has a main method which creates the object of child class.
As its object is created, the compiler will call child’s default constructor which in turn calls its parent class constructor. Following is the output.

Abstract constructor called
Learning abstract constructor


If the child class of abstract class is also abstract, then their constructors will be invoked whenever an object of their concrete(or non-abstract) child class is created.
Refresher

  • A constructor is a method with the same name as that of the class.
  • Difference between a method and constructor is that a constructor does not return a value while a method can.
  • A constructor may be preceded with any of the access specifiers.
  • A private constructor restricts object creation of its class from outside the class.
  • If a class does not contain a constructor, the compiler creates a default constructor which is a does not accept any argument.
  • A class can have more than one constructors with different number or type of arguments. This is called constructor overloading.
  • A constructor may call another constructor of the same or parent class, it is called constructor chaining.
  • Constructors can not be overridden just like method overriding is possible.
  • Interfaces can not have a constructor since they are never instantiated.
  • Abstract class can have a constructor which is invoked when an object of its first concrete child class is created.


Click the clap button below if the article was useful.

2

Mark Your Impression

Close Menu