Sunday 18 December 2016

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

No comments: