What is Constructor and its type?

Constructor in Java:-

A constructor initialize an object when it is created. It has same name as a class and syntactically similar as method. It have no explicit return type.

All classes have constructor, whether you define or note, because java automatically provides a default constructor that initialize all member variable to zero. However once you define your own constructor, the default constructor is no longer used.

Default Constructor:-

For Example:~

class MyClass

{

int x;

MyClass() //Constructor

{

x=10;

}

}

This constructor assigns the instance variable x of MyClass the value 10. This constructor is called by new when object is created.

 

Parameterized Constructor:-

      Constructor that accept one or more parameter is known as parameterized constructor.

For Example:~

class MyClass

{

int x; //instance variable

MyClass(int i) //Constructor

{

x=i;

}

Public static void main(String a[])

{

MyClass m = new MyClass(10);

System.out.println(m.x);

}

}

Note:-  There is no copy constructor in java like in C++ language.

1 Comment

  • My wife and i ended up being lucky that Jordan could conclude his homework using the precious recommendations he gained through the blog. It is now and again perplexing to simply happen to be giving away tactics which often a number of people have been making money from. Therefore we understand we’ve got the writer to give thanks to for that. Most of the explanations you have made, the straightforward site menu, the relationships your site assist to create – it is mostly incredible, and it is making our son in addition to us feel that the subject matter is thrilling, which is quite indispensable. Thanks for the whole lot!

Leave a Reply