Construtor

Constructor in Java 8 with example

Brief Overview:

The constructor in Java play a very important role in object oriented programming , In this post I discuss in detail how constructors are used in Java programming language with an example.

Constructor

It is a special type of method , used to initialise the values of data members of class . We can do this in different ways .

Construtor Types

Default

In this case , all data members are initialised to zero or null ,we can call this explicitly or the compiler will do it automatically.

Example :

class A{
 int a, b ;
 string str;
public A(){
 a=b=0;
str=NULL;
}
}

In the above example ,we initialised the class data members to 0

Parametrised

class Example
{
      private int var;
      //default constructor
      public Example()
      {
             this.var = 10;
      }
      //parameterized constructor
      public Example(int num)
      {
             this.var = num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example obj = new Example();
              Example obj2 = new Example(100);
              System.out.println("var is: "+obj.getValue());
              System.out.println("var is: "+obj2.getValue());
      }
}

The code above illustrates the initialising the values of a, b and str (class members) to x ,y and str1.

Copy Constructor

class Complex { 
  
    private double re, im; 
      
    public Complex(double re, double im) { 
        this.re = re; 
        this.im = im; 
    } 
      
   //copy constructor

    Complex(Complex c) { 
        System.out.println("Copy constructor called"); 
        re = c.re; 
        im = c.im; 
    } 
       
    
    public String toString() { 
        return "(" + re + " + " + im + "i)"; 
    } 
} 
  
public class Main { 
  
    public static void main(String[] args) { 
        Complex c1 = new Complex(10, 15); 
        Complex c2 = new Complex(c1);    
        Complex c3 = c2;    
        System.out.println(c2); 
    } 
} 

The complex number are initialised through the objects.

The Java supports all the above discussed constructors.

Constructor Overloading

Constructor name is same as class same , each constructor will differ by its type and number of arguments. The following example illustrate :

Class test{
     int a,b;
     string str;
  public test(){
    a = b =0;
   str=0;
 }
public test(int x,int y)
{
a=x;
b=y;
}
}
public class main class{
public static void main(String args[])
{
  test t1 = new test();//object creation which calls default constructor .
test t2 = new test(2,4);//Second Object creation creates parametrised constructor.

Constructors in Inheritance

In inheritance ,we use the constructor extensively for the data initialisation , super() is used to access the super class constructor . The following example clarify the usage of the constructors in inheritance.

class Person1 
{ 
    Person1() 
    { 
        System.out.println("Person1 class Constructor"); 
    } 
} 
  
/* subclass Student extending the Person class */
class Student1 extends Person1
{ 
    Student1() 
    { 
        // invoke or call parent class constructor 
        super(); 
  
        System.out.println("Student1 class Constructor"); 
    } 
} 
  

class Test 
{ 
    public static void main(String[] args) 
    { 
        Student1 s = new Student1(); 
    } 
} 

Output

In inheritance we can initialise the data members through super() and directly calling the parent class constructor.

  1. Call to super() should be the first statement in Derived Class constructor. 
  2. If a constructor does not explicitly calls a superclass constructor, the Java compiler automatically inserts a call to the zero-argument constructor of the superclass. If the superclass does not have a zero-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
  3. If a subclass constructor calls a constructor of its superclass, either explicitly or implicitly, we might think that a whole chain of constructors called one by one , all the way back to the constructor of Object. This is called  constructor chaining.

Constructor Chaining

Consider a situation where a base class is extended by a child class. Whenever an object of the child class is created, the constructor of the super class is invoked first before the child class constructor . It is called Constructor chaining.

class DemoChain{
   int  value1;
   int  value2;
    DemoChain(){
      value1 = 1;
      value2 = 2;
      System.out.println("Inside 1st Parent Constructor");
   }
   DemoChain(int a){
      value1 = a;
      System.out.println("Inside 2nd Parent Constructor");
   }
  public void display(){
     System.out.println("Value1 === "+value1);
     System.out.println("Value2 === "+value2);
  }
  public static void main(String args[]){
     DemoChild d1 = new DemoChild();
     d1.display();
  }
}
class DemoChild extends DemoChain{
    int value3;
    int value4;
    DemoChild(){
  
     value3 = 3;
     value4 = 4;
    System.out.println("Inside the Constructor of Child");
    }
    public void display(){
      System.out.println("Value1 === "+value1);
      System.out.println("Value2 === "+value2);
      System.out.println("Value1 === "+value3);
      System.out.println("Value2 === "+value4);
   }
}

Conclusion

The constructors plays a important role in data initialisation , the concept is little bit complicated ,but the above example clearly clarify the concepts of constructors in inheritance .

Image by wikipedia.