How do I call one constructor from another in Java?

Submitted 3 years, 6 months ago
Ticket #251
Views 279
Language/Framework Java
Priority Low
Status Closed

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor ?

Submitted on Oct 19, 20
add a comment

2 Answers

Verified

Yes:

public class Foo {

    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }

}

Submitted 3 years, 6 months ago

Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor. This is known as constructor overloading.

calling a constructor from the another constructor of smae class is known as Constructor chaining.

// Java program to illustrate Constructor Chaining

// within same class Using this() keyword

class Temp

{

    // default constructor 1

    // default constructor will call another constructor

    // using this keyword from same class

    Temp()

    {

        // calls constructor 2

        this(5);

        System.out.println("The Default constructor");

    }

  

    // parameterized constructor 2

    Temp(int x)

    {

        // calls constructor 3

        this(5, 15);

        System.out.println(x);

    }

  

    // parameterized constructor 3

    Temp(int x, int y)

    {

        System.out.println(x * y);

    }

  

    public static void main(String args[])

    {

        // invokes default constructor first

        new Temp();

    }

}

output

75
5
The Default constructor

Submitted 3 years, 6 months ago


Latest Blogs