Constructor in Java
Constructor in Java
class Student3
{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display(); Output:
} } 0 null
0 null
Parameterized constructor:
• There are many ways to copy the values of one object into
another in java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
Copy the values of one object into another using 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);}
Output:
111 Karan
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
111 Karan
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Copying by assigning the values of one object into another :
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}