google.com, pub-8786015629279405, DIRECT, f08c47fec0942fa0 Copy Constructor in Java

Copy Constructor in Java

0
Copy Constructor in Java



Copy Constructor

There is no copy constructor in java. But we can copy the value one object to another object like copy constructor in C++.
There are many way to create a copy constructor in java.

  1. By constructor
  2. By assigning value from one object to other
  3. Using clone() Method of object class.


Example Copy Constructor  by Constructor

Example:
//Java program to copy constructors  
class Student{  
    int id;  
    String name;  
    int age; 
 Student(int i, String n, int a ){  
    id = i;  
    name = n;  
    age= a;  
    }  
      
    Student(Student s){  
    id = s.id;  
    name = s.name;  
    age= s.age;  
    }  
void display(){System.out.println(id+" "+name+" "+age);} 
class const{
    public static void main(String args[]){  
    Student s1 = new Student(111, “Karan”, 25);
    Student s2 = new Student(s1);  
    s1.display();  
    s2.display();
}  
}


Output:
 111,Karan,25
 111,Karan,25

Example Copy Constructor without constructor or using object value

Example:
//Java program to copy constructors  
class Student{  
    int id;  
    String name;  
    int age; 
 Student(int i, String n, int a ){  
    id = i;  
    name = n;  
    age= a;  
    }  
    
    
    Student(){ }

class const{
    public static void main(String args[]){  
    Student s1 = new Student(111, “Karan”, 25);
    Student s2 = new Student();  
    s2.id=s1.id;    
   s2.name=s1.name;     
    s2.age=s1.age;
    s1.display();
    s2.display();
}  
}

Output:
 111,Karan,25
 111,Karan,25

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Thank you for your interest 😊

We will back shortly after reviewing...

Thank you for your interest 😊

We will back shortly after reviewing...

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top