×

Java Programs

Java Practice

Java program to implement constructor chaining

Learn how to implement constructor chaining in Java?
Submitted by Nidhi, on March 21, 2022

Problem statement

In this program, we will create a Sample class and implement constructor chaining using "this" keyword.

Source Code

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

// Java program to implement 
// constructor chaining

class Sample {
  int num1;
  int num2;

  Sample() {
    this(10);
    System.out.println("Default constructor called");
  }

  Sample(int n1) {
    this(n1, 20);
    System.out.println("Parameterized constructor called: 1");
  }

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

    System.out.println("Parameterized constructor called: 2");
  }

  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 obj = new Sample();
    obj.printValues();
  }
}

Output

Parameterized constructor called: 2
Parameterized constructor called: 1
Default constructor called
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 num1, num2, and implemented constructor chaining using the "this" keyword.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created an object obj. We initialized data members of obj using constructor chaining and printed the result.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.