Saturday, 15 June 2013

What is Constructor? What are its features? Explain various types of constructor implements in Java with example?



A constructor is a special method that initializes an object immediately upon creation.It has the same name as the class in which it resides and is syntactially similar to a method.The main purpose of the constructor is to set the initial state of an object when the object is created with the help of new operator.
Features Of Constructor:-
1.       It is a special function with the same name of the class.
2.      These are called automatically whenever an instance or object of class is created.
3.      No separate call statement is used to execute the constructor.
4.     It doesnot have any return type.
There are three types of constructor in Java:-
1.       Default Constructor : that accepts no parameters.
2.      Constructor with Arguments : that accepts parameters.
3.      Copy Constructor : it is used to declare and initialize an object from another object.
Example :-
class a
{
int l,b;
a(int lt,int br)
{
l=lt;
b=br;
}
a(a obj)
{
l=obj.l;
b=obj.b;
}
void area()
{
System.out.println(l*b);
}}
class k
{
public static void main(String args[])
{
a obja=new a(5,6);
obja.area();
a objb=new a(obja);
objb.area();
}}

No comments:

Post a Comment