Constructor Chaining in Java Using 'this' Keyword

사용하여 응답함: GPT-4o-mini에 의해Java Q&A Hub

질문:

How can constructor chaining be done using this keyword In Java?

답변:

In Java, constructor chaining refers to the practice of calling one constructor from another constructor within the same class or from a superclass. This can be achieved using the this keyword. When you use this() in a constructor, it allows you to call another constructor in the same class.

Here’s how you can implement constructor chaining using the this keyword:

Example of Constructor Chaining

class Example {
    private int a;
    private int b;

    // First constructor
    public Example() {
        this(0, 0); // Calls the second constructor with default values
        System.out.println("Default constructor called");
    }

    // Second constructor
    public Example(int a) {
        this(a, 0); // Calls the third constructor with a and default value for b
        System.out.println("Constructor with one parameter called");
    }

    // Third constructor
    public Example(int a, int b) {
        this.a = a;
        this.b = b; // Initializes the instance variables
        System.out.println("Constructor with two parameters called");
    }

    public void display() {
        System.out.println("a: " + a + ", b: " + b);
    }

    public static void main(String[] args) {
        Example obj1 = new Example(); // Calls the default constructor
        obj1.display();

        Example obj2 = new Example(5); // Calls the constructor with one parameter
        obj2.display();

        Example obj3 = new Example(5, 10); // Calls the constructor with two parameters
        obj3.display();
    }
}

Explanation

  1. Default Constructor: The first constructor (Example()) calls the second constructor (Example(int a, int b)) with default values (0, 0). This is done using this(0, 0).

  2. Single Parameter Constructor: The second constructor (Example(int a)) calls the third constructor (Example(int a, int b)) with the value of a and a default value for b (0). This is done using this(a, 0).

  3. Two Parameters Constructor: The third constructor initializes the instance variables a and b.

  4. Display Method: The display() method is used to print the values of a and b.

  5. Main Method: In the main method, different constructors are called to demonstrate constructor chaining.

Key Points

  • You can only call one constructor from another using this() in a constructor.
  • The call to this() must be the first statement in the constructor.
  • Constructor chaining helps to reduce code duplication and makes the code cleaner and more maintainable.