Sunday 18 December 2016

Difference between Constructors and Static block


1. Constructor - Called when we create object for the class
    Static block - Called when the class is loaded in the memory even before the constructor.

2. Constructor - Name of the constructor should be same as the class name.
     Static block - No name is there for static block. Only static{} keyword is used for the declaration.

3. Constructor - Multiple constructor with different signatures can be present in same class.
     Static block - There can be many static block in a class.
Constuctor in Java:

A constructor should have same name as the class without any return type.

The constructor is called immediately after the object creation for the class.

The constructor is a block of code used to instantiate the variables in the class.

Constructor can be created with parameters and without parameters.

There can be more that one constructor for a single class as we do for method overloading with different signatures.

It is a block of code that gets executed during the object creation, but this executes after the static block. (Static block gets executed immediately when the class is loaded in memory)


Example for constructor:


public class constructorExample {
//static block
static{
System.out.println("Static block is called when the class is loaded in the memory.");
}
    //Constructor without parameter
public constructorExample() {
System.out.println("Const with no args");
}
//Constructor with paramerter
public constructorExample(String name) {
System.out.println("Name: " + name);
}
public static void main(String args[]) {
constructorExample ce = new constructorExample();
constructorExample ce1 = new constructorExample("Karthikeyan");
}


}



Output:

Static block is called when the class is loaded in the memory.
Const with no args
Name: Karthikeyan