Tuesday, 7 April 2015

Constructor in Java

In Java there is a special method provided to initialize objects when they are created. This special method which helps in automatic initialization is called Constructor.

Constructor has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a method.

When is Constructor called?

Constructor is called automatically when the object is created, before the new operator completes.

No Return Type

Constructors don't have a return type, even void is not allowed. Constructors have an implicit return type which is the class type (current instance) itself.

Constructor Example
public class ConstrExample {
        int i;
 String name;
 public ConstrExample() {
  System.out.println("Creating an object");
  System.out.println("i - " + i + " name - " + name);
 }
  

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConstrExample constrExample = new ConstrExample();

 }
}

Here Constructor is this part

public ConstrExample() {
 System.out.println("Creating an object");
 System.out.println("i - " + i + " name - " + name);
}

And executing this program will give the output as -

Creating an object
i - 0 name - null

Note here that -

  • Constructor name is same as the class name.
  • Here the access modifier is given as public, but construcor can take private, protected or default access modifier.
  • If void is given as the retrun type then compiler would not treat it as a constructor but a method. In that case Java compiler will add a default constructor.
  • Constructor can't be final.

Default Constructor

When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class. If a constructor is explicitly defined for a class, then the Java compiler will not insert the default no-argument constructor into the class.

Parameterized Constructor

If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.
A class can have multiple constructors too as long as constructor signatures are different.

Parameterized Constructor Example
public class ConstrExample {
 int i;
 String year;
 ConstrExample(int i, String year) {
  System.out.println("Creating a parameterized object");
  this.i = i;
  this.year = year;
  System.out.println("i - " + i + " year - " + year);
 }
 ConstrExample() {
  System.out.println("Creating a object");  
  System.out.println("i - " + i + " year - " + year);
 }
  

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConstrExample constrExample1 = new ConstrExample(10, "2015");
  ConstrExample constrExample2 = new ConstrExample();
  
 }
}

And executing this program will give the output as -

Creating a parameterized object
i - 10 year - 2015
Creating a object
i - 0 year - null

Note here that -

  • There are 2 constructors here one with parameters another no-arg constructor, this is known as constructor overloading.
  • 2 Objects are created one with parameters which will invoke the parameterized constructor and another without any parameters which will invoke the no-arg contructor.

Constructor Chaining

In case when we have a hierarchy of classes it is important to know what is the order in which the constructors for the classes are executed. That order is known as constructor chaining.
As exp. if class A is superclass and there is Class B which is subclass of A. What is the order in which constructors of Class A and Class B are executed?
Answer is, the order followed is from superclass to subclass.

Subclass can call a constructor in the superclass inside one of the subclass constructors using super(). In that case super() must be the first statement in a subclass constructor. If super() is not used then the default no-arg constructor of each superclass will be executed. Note that the order remains same (from superclass to subclass ) whether or not super() is used.

Let's see it with an example

class A{
 A(){
  System.out.println("In class A's constructor");
 }
}

class B extends A{
 B(){
  System.out.println("In class B's constructor");
 }
}
class C extends B{
 C(){
  System.out.println("In class C's constructor");
 }
}
public class ConstrChaining {

 /**
  * @param args
  */
 public static void main(String[] args) {
  C c = new C();

 }

}

And executing this program will give the output as -

In class A's constructor
In class B's constructor
In class C's constructor

Points to note -

  • Constructor has the same name as the class in which it is created.
  • Constructor is called automatically when the object is created, in order to initialize an object.
  • Constructors don't have a return type, even void is not allowed.
  • Constructor can have any access modifier public, private, protected or default.
  • When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class, that is called default constructor.
  • Within the same class there may be multiple constructors where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.
  • In case of inheritance, constructors are called in order of super class to sub class, that process is known as Constructor chaining.

That's all for this topic Constructor in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. Constructor chaining in Java
  2. Constructor overloading in Java
  3. Initializer block in Java
  4. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment