A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Java program to implement constructor chaining
Q:

Java program to implement constructor chaining

0

Java program to implement constructor chaining

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to implement a copy constructor is given below. The given program is compiled and executed successfully.

// 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

Explanation:

In the above program, we created a Sample class and public class Main. The Sample class contains data members num1num2, and a parameterized constructor, a copy constructor, a method printValues().

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created 2 objects obj1obj2. We initialized data members of obj1 using parameterized constructor and initialized object obj2 using the copy constructor. After that, we printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now