Categories
constructor java

How do I call one constructor from another in Java?

2556

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 (if there are several ways to do it)?

5

  • 2

    I believe the premise of your question is wrong. Instead of calling a constructor within a constructor, use the Factory pattern. A static factory method first creates all lower-level objects. Then it constructs the higher-level objects which gets returns from the factory call. This technique removes complexity from the model which aids maintenance, clarity, and testing.

    Jul 6, 2018 at 19:49

  • 1

    I generally switched to private constructors and factory methods, since constructors, because of their limitations, are violating the open-closed principle. I think this comment should be the correct answer, everything else will confuse the hell out of your team mates.

    – Richard

    Jan 21, 2019 at 12:27


  • Sroy but that’s not a good practice if you want to do something like that, overcharge the constructor. If you want to wrap a content, that could be done, but for another pourpuse. Not the constructor public class Foo { private int x; public Foo() { } public Foo(int x) { this.x = x; } public Foo(int x, int y) { this.x = x; this.y = y }

    – Augusto

    Jul 24, 2019 at 19:16

  • 1

    Calling a constructor from another constructor in Java is primarily a means of providing default values for parameters to the one constructor that should actually construct your object, and then it should be enough to just assign values in the constructor’s body. If your object requires complex construction, that’s a code smell indicating that your class lacks cohesion. If a constructor is not enough for you, you’ve probably done a poor job of designing your classes which you will discover when it’s time to make changes down the road.

    – Stuporman

    Mar 18, 2021 at 16:36

  • Instead of using “this” why cant we just use new, for eg inside no-arg constructor call new Foo(5); is this correct? if not why so? @peter

    – abc123

    Oct 4, 2021 at 17:47


3284

Yes, it is possible:

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

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

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

20

  • 38

    So I supposed it’s not possible to call a super constructor and another constructor of the same class as both need to be the first line?

    Nov 2, 2012 at 18:02

  • 37

    @gsingh2011: Indeed. You can only chain to one other constructor.

    – Jon Skeet

    Nov 2, 2012 at 18:06

  • 51

    This has to appear on the first line, but you can do calculations in the constructor before it is called: You can use static methods in the arguments of this() on the first line and encapsulate any calculation which has to be performed before the call to the other constructor in that static method. (I have added this as a separate answer).

    Mar 11, 2013 at 20:34


  • 10

    @gsingh2011 I know it’s late but as a way around, you can call overloaded constructor using this(…) and then in that overloaded constructor, you can make a call to base class’ constructor using super(…)

    – Ali

    May 13, 2013 at 7:23

  • 3

    @Andrej: That would indeed be “calling one constructor from another” but it wouldn’t be doing what the OP wants, which is to initialize a single object via multiple constructors, one chaining to another. Creating two objects by just creating a separate object within one constructor call isn’t the same thing at all.

    – Jon Skeet

    Sep 26, 2019 at 22:10

283

Using this(args). The preferred pattern is to work from the smallest constructor to the largest.

public class Cons {

    public Cons() {
        // A no arguments constructor that sends default values to the largest
        this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
    }

    public Cons(int arg1, int arg2) {
       // An example of a partial constructor that uses the passed in arguments
        // and sends a hidden default value to the largest
        this(arg1,arg2, madeUpArg3Value);
    }

    // Largest constructor that does the work
    public Cons(int arg1, int arg2, int arg3) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
    }
}

You can also use a more recently advocated approach of valueOf or just “of”:

public class Cons {
    public static Cons newCons(int arg1,...) {
        // This function is commonly called valueOf, like Integer.valueOf(..)
        // More recently called "of", like EnumSet.of(..)
        Cons c = new Cons(...);
        c.setArg1(....);
        return c;
    }
} 

To call a super class, use super(someValue). The call to super must be the first call in the constructor or you will get a compiler error.

6

  • 31

    If many constructor parameters are used, consider a builder. See Item 2 of “Effective Java” by Joshua Bloch.

    – koppor

    Nov 13, 2012 at 20:16

  • 6

    The problem with the implementation of the last approach using the factory method, newCons, is that you are trying to change state of an object, using setArg1(...), that should most likely have its fields set as final. As we are trying to keep as much as possible of an object immutable, if not completely, a builder pattern will address this issue more correctly.

    – YoYo

    Jan 30, 2016 at 6:46

  • 2

    Wouldn’t you rather do :: public Cons() { this(madeUpArg1Value,madeUpArg2Value); }

    Apr 16, 2018 at 13:31


  • 3

    @RodneyP.Barbati It’s pretty common in Java for lower-arity constructors to call greater-arity constructors and then do nothing else. if a class K has, e.g., two final fields a, b, then the “general constructor” would be K(A a, B b) { this.a = a; this.b = b; }. Then, if b has a reasonable default, there can be a one-arg constructor K(A a) { this(a, DEFAULT_B); }, and if there’s a default a as well, we have a default constructor: K() { this(DEFAULT_A); }. That’s a pretty common convention in Java.

    May 17, 2018 at 13:12

  • @RodneyP.Barbati If you have a final field (so that it must be set), then the default constructor would have to set it. If your higher-arity constructors call the default constructor (which would have to be done before anything else), then the higher-arity constructors never have any options to set any of those fields.

    May 17, 2018 at 13:14

235

[Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).]

In Java another constructor of the same class can be called from a constructor via this(). Note however that this has to be on the first line.

public class MyClass {

  public MyClass(double argument1, double argument2) {
    this(argument1, argument2, 0.0);
  }

  public MyClass(double argument1, double argument2, double argument3) {
    this.argument1 = argument1;
    this.argument2 = argument2;
    this.argument3 = argument3;
  }
}

That this has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:

public class MyClass {

  public MyClass(double argument1, double argument2) {
    this(argument1, argument2, getDefaultArg3(argument1, argument2));
  }

  public MyClass(double argument1, double argument2, double argument3) {
    this.argument1 = argument1;
    this.argument2 = argument2;
    this.argument3 = argument3;
  }

  private static double getDefaultArg3(double argument1, double argument2) {
    double argument3 = 0;

    // Calculate argument3 here if you like.

    return argument3;

  }

}

5

  • 16

    It’s true that you can call static methods in this way in order to perform complex calculations for argument values, which is fine. However, if one feels that code is needed before constructor delegation (this(...)) then it would be reasonable to assume that an horrible mistake has been made somewhere and that the design perhaps needs a bit of a rethink.

    Jun 8, 2016 at 23:00

  • 16

    I would agree that a very complex transformation likely indicates a design issue. But 1) there are some simple transformations which for which this may be useful – not all constructors are just linear projection on others and 2) there may be other situation where this information could become hand, like supporting legacy code. (While I agree on your conclusion, I do not see why it would justify a down vote).

    Jun 16, 2016 at 17:36


  • 2

    @RodneyP.Barbati: I see a few issues in doing it the way you describe it: a) Doing it that way it is not possible to illustrate the use of static method in a constructor (and that is the intention of the example) 😉 and b) if you do it your way, the fields cannot be final (final fields can be initialized only once).

    Jun 13, 2018 at 6:06

  • 1

    @RodneyP.Barbati: Two other aspects: c) I believe that you should always do the object initialisation at a single point, which has to be the most general constructor. If object initialisation requires a complex task (object init not being lazy) or checking or acquiring some resources (like a file), then you like to do that only once. And d) Adding another argument (say argument4) for which the initialisation depends on the value of argument1 to argument3 you would have to change all constructors in your case, whereas here you only have to add one and let the 3-arg call the 4-arg constructor.

    Jun 13, 2018 at 8:13


  • For more general method of overcoming the “must be first statement in constructor” limitation, see this answer. It applies to both super() and this() calls.

    Jul 29, 2018 at 1:34