Constructors and Destructors in java

 Constructors and Destructors:

Constructors are methods having same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. They have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. Other properties of constructor are same as simple methods like they can have parameters and overloading.

Types of Constructor

There are two types of constructors depending upon the type we can add and remove variables.

  • Default Constructor
  • Parameterised Constructor
1. Default Constructor
This is the one type of constructor. By default without any parameters, this constructor takes place. This constructor does not have any parameters in it.
2. Parameterised Constructor

As the name suggest parameterised constructor has some parameters or arguments at the time of initialising the object.

Destructors are methods, called when object is destroyed. For Destructor Java provides a mechanism called finalisation. It provides a finalise() method which acts as destructor is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalise( ) will be executed. So seldom used.

Example:

class Rectangle

 {

int height, width;

Rectangle(int recHeight, int recWidth) //Constructor to initilize

{

System.out.println("Constructor is called object is going to initialized");

height = recHeight;

width = recWidth;

}

protected void finalize()

{

 System.out.println("Finalize is called object is going to destroy.");

 }

void showRec() //Simple Method

{

 System.out.println("Height = " + height + " Width = " + width); 

}

public static void main(String args[])

{

Rectangle myRec = new Rectangle(4,5);

myRec.showRec();

}

}

Post a Comment

Please do not enter any spam link in the comment box