Constructors - rahul00773/JavaConcepts GitHub Wiki

Constructors

Once we creates an object compulsory we should perform initialization. Then only the object is in a position to response properly.

Whenever we are creating an object some piece of the code will be executed automatically to perform initialisation of the object. This piece of the code is nothing but constructor. Hence the main purpose of constructor is to perform initialisation of an object.

package src.constructor;

public class Student {

String name;
int rollNo;

Student(String n, int r){

    this.name = n;

    this.rollNo=r;
}


public static void main(String[] args){

    Student s1 = new Student("rahul",101);
    Student s2 = new Student("kumar",102);
}

}

Note: The main purpose of constructor is to perform initialisation of an object. But not to create object.

Difference between constructor and instance block:

  1. The main purpose of construct is to perform initialisation of an object. But other than initialization if we want to perform any activity for every object creation then we should go for Instance block.(Like updating one entry in the database for every object creation are incrementing count value for every object creation etc)
  2. Both constructor and instance block have their different purposes and replacing one concept with another concept may not work always.
  3. Both constructor and instance block will be executed for every object creation. But instance block first followed by constructor.

Demo Program to Print number of object created for a class.

package src.constructor;

public class Test {

public static int count=0;

{
    count++;
}

Test(){

}

Test(int i){

}

Test(double d){

}

public static void main(String[] args){


    Test t = new Test();
    Test t1 = new Test(10);
    Test t2= new Test(10.5);


    System.out.println("number of object created : " + count);
}

}

Rules of Writing for constructor:

  1. Name of the class and the name of constructor must be matched.
  2. Return type concept not applicable for constructor even void also
  3. By mistake if we are trying to declare return type for the constructor then we won’t get any compile time error. Because compiler treats it as a method. Hence it is legal(but stupid) to have a method whose name is exactly same as class name.

package src.constructor;

public class Test1 {

/**
 * It's a method but not constructor
 */
void Test1(){ 

}


public static void main(String[] args){

    Test1 t = new Test1();
}

}

The only applicable modifiers for constructor are public, private protected default. If we are trying to use any other modifier we will get compile time error.

class Test{

static Test(){

}

}

CE: modifier static not allowed here

Default Constructor:

  1. The compiler is responsible to generate default constructors.(but Not JVM)
  2. If we are not writing any constructor then the only compiler will generate default constructor. That is if we are writing at least one constructor then the compiler won’t generate default constructor.
  3. Hence every class in java can contain constructors. It may be a default constructor generated by a compiler or customized constructor provided by the programmer. But not both simultaneously.

A prototype of Default Constructor:

  1. It is always no-arg constructor.
  2. The access modifiers of the default constructor are exactly the same as the access modifier of class. (This rule is applicable only for public and default)
  3. It contains only one line - “super();”. It is a no-argument call to superclass constructor.
Programmer Code Compiler Code
class Test{ } class Test{Test(){Super();}}
public class Test{}. public class Test{Test(){Super();}}
public class Test{void Test({}} public class Test{Test(){Super();}void Test(){}}
class Test{Test(){}}. class Test{Test(){Super();}}
class Test{Test(int i){Super();}} class Test{Test(int i){Super();}}
class Test{Test(){this(10);Test(int I){}} class Test{Test(){this(10);}Test(int I){Super();}}

The first line inside every constructor should be either super or this. And we are not writing any thing then compiler will always place super();

Case1.

We can take super(); or this only in the first line of constructor. If we are trying to take anywhere else we will get compile-time error.

CE: call to super must be the first statement in the constructor.

Example:

class Test{

Test(){ System.out.println(“hello”); // Compile time error :call to super must be first statement in constructor.

super(); }

}

Case2: With a constructor we can take either super(); or this but not both simultaneously.

class Test{

Test(){

super(); this(); //Compile time error : call to this must be first statement in constructor.

}

}

Case3: We can use super(); or this(); only inside constructor. If we are trying to use outside of constructor we will get compile time error.

class Test{

public void m1(){

super(); // Compile time error :call to super must be first statement in constructor.

System.out.prinln(“hello”);
}

}

That is: We can call constructor directly from another constructor only.

super(); // Only in Constructor

this(); // Only in first line

Only one but both not simultaneouly

super(), this(). super,this
These are constructors call to call superclass and current class constructors these are keywords to refer superclass and current class instance members
We can use only in constructors as first line We can use anywhere expect static area
We can use only once in construction We can use any number of times

class Test{

public static void main(String[] args){

System.out.println(super.hasCode()); // compile time error.: Non -static variable super can not be referenced from a static context }

}