Java Program to Implement a Copy Constructor

You are currently viewing Java Program to Implement a Copy Constructor

Java program to implement a copy constructor

// Java program to implement a 
// copy constructor

class Sample {
  int num1;
  int num2;

  Sample(int n1, int n2) {
    this.num1 = n1;
    this.num2 = n2;
  }

  Sample(Sample obj) {
    this.num1 = obj.num1;
    this.num2 = obj.num2;
  }

  void printValues() {
    System.out.println("Data members: ");
    System.out.println("Num1: " + num1);
    System.out.println("Num2: " + num2 + "\n");
  }
}

class Main {
  public static void main(String args[]) {
    Sample obj1 = new Sample(10, 20);
    Sample obj2 = new Sample(obj1);

    obj1.printValues();
    obj2.printValues();
  }
}

Output

Data members: 
Num1: 10
Num2: 20

Data members: 
Num1: 10
Num2: 20

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply