What is Constructor?
A constructor is a block of Code which is similar to the method and it is called when an instance of object is created. if there is no constructor in the class compiler automatically creates default constructor. Constructors, basically is used to initialize the object and it's name must be same as class name and must not have an explicit return type.
Constructor Overloading
when there is more than one constructor which differ on the basis of parameters (constructor of the same class) than it is called as constructor overloading:
example:-
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Copy Constructor
there is no such thing as "Copy Constructor" in java, although we can copy values of one object to another object.
this can be done by:
- constrcutor
- clone method
assigning values of one object into another
in this example we will copy value of one object into another by using a simple java constructor:-
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display(); } }