A constructor behaves like a method where a class name and method name must be the same.
Characteristics of Constructor:
1. Whenever an object of class being created, constructor will call & execute automatically.
2. No need object to call constructor.
3. No return allowed with the name of constructor, not even void.
Uses of Constructor:
1. Default value Setting.
2. One time execution program may be written inside the constructor.
Types of Constructor:
1. Default Constructor.
2. Parameterized Constructor.
3. Copy Constructor.
Default Constructor: A Constructor have no parameter is called Default constructor.
Example:
class Test {
Test() {
System.out.println(“Default constructor”);
}
}
class a {
public static void main(String args[]) {
Test obj=new Test();
}
}
Parameterized Constructor: A constructor has one or more parameter is called a parameterized constructor.
Example:
class add {
int a,b,c;
add() {
a=0;
b=0;
System.out.println(a+b);
}
add(int x,int y) {
a=x;
b=y;
System.out.println(a+b);
}
add(int x,int y, int z)
{
a=x;
b=y;
c=z;
System.out.println(a+b+c);
}
}
Copy Constructor: It is same as parameterized Constructor but in parameter, we will pass an object of a class.
class add {
int a,b,c;
add() {
a=0;
b=0;
System.out.println(a+b);
}
add(int x,int y) {
a=x;
b=y;
System.out.println(a+b);
}
add(int x,int y, int z) {
a=x;
b=y;
c=z;
System.out.println(a+b+c);
}
add( add obj) {
a=obj.a;
b=obj.b;
c=obj.c;
System.out.println(a+b+c);
}
}
class test {
public static void main(String args[]) {
add obj=new add();
add obj1=new add(2,4);
add obj2=new add(2,3,4);
add obj3=new add(obj1);
}
}