By ashokgelal


2008-11-12 20:10:19 8 Comments

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)?

19 comments

@rogerdpack 2019-04-09 00:30:59

Originally from an anser by Mirko Klemm

Just for completeness: There is also the Instance initialization block that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.

So in your case

{ 
  System.out.println("this is shared constructor code executed before the constructor");
  field1 = 3;
}

There is also a "static" version of this to initialize static members: "static { ... }"

@GetBackerZ 2017-11-21 14:03:51

Pretty simple

public class SomeClass{

    private int number;
    private String someString;

    public SomeClass(){
        number = 0;
        someString = new String();
    }

    public SomeClass(int number){
        this(); //set the class to 0
        this.setNumber(number); 
    }

    public SomeClass(int number, String someString){
        this(number); //call public SomeClass( int number )
        this.setString(someString);
    }

    public void setNumber(int number){
        this.number = number;
    }
    public void setString(String someString){
        this.someString = someString;
    }
    //.... add some accessors
}

now here is some small extra credit:

public SomeOtherClass extends SomeClass {
    public SomeOtherClass(int number, String someString){
         super(number, someString); //calls public SomeClass(int number, String someString)
    }
    //.... Some other code.
}

Hope this helps.

@Rodney P. Barbati 2019-01-22 08:51:30

I don't like this approach because calling either of the constructors leaves one of the values uninitialized - in other words, you get an invalid object. Either of the one parameter constructors should call the two parameter constructor by passing null for one of the values. This way, you are guaranteed that all of the values are initialized in one place correctly.

@GetBackerZ 2019-01-23 15:49:43

@RodneyP.Barbati if i initialize the variables does that improve upon this issue you are addressing?

@Josh 2008-11-12 20:13:22

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.

@koppor 2012-11-13 20:16:00

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

@YoYo 2016-01-30 06:46:25

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.

@LordHieros 2018-04-16 13:31:23

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

@Rodney P. Barbati 2018-04-23 18:17:23

Initialization should proceed from least to greatest - I would never have a default constructor call up the chain to a multi-parameter constructor. What needs to happen is that all constructors call either the default or a constructor with less parameters.

@Joshua Taylor 2018-05-17 13:12:55

@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.

@Joshua Taylor 2018-05-17 13:14:48

@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.

@Hong 2018-12-04 20:03:42

This one works with Android Studio while the accepted answer does not. Not sure why.

@S R Chaitanya 2017-01-07 13:21:18

Yes it is possible to call one constructor from another. But there is a rule to it. If a call is made from one constructor to another, then

that new constructor call must be the first statement in the current constructor

public class Product {
     private int productId;
     private String productName;
     private double productPrice;
     private String category;

    public Product(int id, String name) {
        this(id,name,1.0);
    }

    public Product(int id, String name, double price) {
        this(id,name,price,"DEFAULT");
    }

    public Product(int id,String name,double price, String category){
        this.productId=id;
        this.productName=name;
        this.productPrice=price;
        this.category=category;
    }
}

So, something like below will not work.

public Product(int id, String name, double price) {
    System.out.println("Calling constructor with price");
    this(id,name,price,"DEFAULT");
}

Also, in the case of inheritance, when sub-class's object is created, the super class constructor is first called.

public class SuperClass {
    public SuperClass() {
       System.out.println("Inside super class constructor");
    }
}
public class SubClass extends SuperClass {
    public SubClass () {
       //Even if we do not add, Java adds the call to super class's constructor like 
       // super();
       System.out.println("Inside sub class constructor");
    }
}

Thus, in this case also another constructor call is first declared before any other statements.

@John McClane 2018-07-29 01:14:04

You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword (when you need to call a constructor from a superclass).

However, such a call must be the first statement of your constructor. To overcome this limitation, use this answer.

@Utsav 2016-11-16 16:14:17

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.

Example:

Class Test {
    Test() {
        this(10); // calls the constructor with integer args, Test(int a)
    }
    Test(int a) {
        this(10.5); // call the constructor with double arg, Test(double a)
    }
    Test(double a) {
        System.out.println("I am a double arg constructor");
    }
}

This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.

@Omar Faroque Anik 2018-06-06 19:36:32

It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:

 public Omar(){};
 public Omar(a){};
 public Omar(a,b){};
 public Omar(a,b,c){};
 public Omar(a,b,c,d){};
 ...

You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e

@Akash Manngroliya 2016-09-13 05:48:26

Yes it is possible to call one constructor from another with use of this()

class Example{
   private int a = 1;
   Example(){
        this(5); //here another constructor called based on constructor argument
        System.out.println("number a is "+a);   
   }
   Example(int b){
        System.out.println("number b is "+b);
   }

@Negi Rox 2018-01-24 05:45:57

I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.

    import java.util.*;
    import java.lang.*;

    class Test
    {  
        public static void main(String args[])
        {
            Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
            Dog cs = new Dog("Bite"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.

            // You need to Explicitly tell the java compiler to use Argument constructor so you need to use "super" key word
            System.out.println("------------------------------");
            Cat c = new Cat();
            Cat caty = new Cat("10");

            System.out.println("------------------------------");
            // Self s = new Self();
            Self ss = new Self("self");
        }
    }

    class Animal
    {
        String i;

        public Animal()
        {
            i = "10";
            System.out.println("Animal Constructor :" +i);
        }
        public Animal(String h)
        {
            i = "20";
            System.out.println("Animal Constructor Habit :"+ i);
        }
    }

    class Dog extends Animal
    {
        public Dog()
        {
            System.out.println("Dog Constructor");
        }
        public Dog(String h)
        {
            System.out.println("Dog Constructor with habit");
        }
    }

    class Cat extends Animal
    {
        public Cat()
        {
            System.out.println("Cat Constructor");
        }
        public Cat(String i)
        {
            super(i); // Calling Super Class Paremetrize Constructor.
            System.out.println("Cat Constructor with habit");
        }
    }

    class Self
    {
        public Self()
        {
            System.out.println("Self Constructor");
        }
        public Self(String h)
        {
            this(); // Explicitly calling 0 args constructor. 
            System.out.println("Slef Constructor with value");
        }
    }

@Shiva Nandam Sirmarigari 2016-11-21 13:14:34

I will tell you an easy way

There are two types of constructors:

  1. Default constructor
  2. Parameterized constructor

I will explain in one Example

class ConstructorDemo 
{
      ConstructorDemo()//Default Constructor
      {
         System.out.println("D.constructor ");
      }

      ConstructorDemo(int k)//Parameterized constructor
      {
         this();//-------------(1)
         System.out.println("P.Constructor ="+k);       
      }

      public static void main(String[] args) 
      {
         //this(); error because "must be first statement in constructor
         new ConstructorDemo();//-------(2)
         ConstructorDemo g=new ConstructorDemo(3);---(3)    
       }
   }                  

In the above example I showed 3 types of calling

  1. this() call to this must be first statement in constructor
  2. This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.

Note: this must be the first statement in the constructor.

@S R Chaitanya 2017-01-07 13:31:52

You have the following in the main method: //this(); error because "must be first statement in constructor This statement does not make much sense. If you are trying to say that this() cannot be called from inside main method, then yes it cannot be because main is static and will not have reference to this()

@Rodney P. Barbati 2019-01-22 08:57:48

@ S R Chaitanya - he is saying that the line of code that contains this(); must be the first line in the overriding constructor. You are also correct that the this keyword is meaningless in a static method.

@Rodney P. Barbati 2017-11-13 23:01:22

There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.

With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.

class LambdaInitedClass {

   public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
       init.accept(this);
   }
}

Call it with...

 new LambdaInitedClass(l -> { // init l any way you want });

@S. Mayol 2017-03-14 23:53:16

The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.

Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.

Setter methods or constructors

@Akshay Gaikwad 2017-03-03 09:27:30

Calling constructor from another constructor

class MyConstructorDemo extends ConstructorDemo
{
    MyConstructorDemo()
    {
        this("calling another constructor");
    }
    MyConstructorDemo(String arg)
    {
        System.out.print("This is passed String by another constructor :"+arg);
    }
}

Also you can call parent constructor by using super() call

@Jon Skeet 2008-11-12 20:12:14

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.

@gsingh2011 2012-11-02 18:02:31

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?

@Jon Skeet 2012-11-02 18:06:07

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

@Christian Fries 2013-03-11 20:34:27

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).

@Ali 2013-05-13 07:23:05

@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(...)

@Trikaldarshi 2013-07-16 21:38:45

@JonSkeet Yes! we can chain to one other constructor but actually we can have a very long chain

@Jon Skeet 2013-07-16 21:46:55

@Mohit: And why is that a problem? It's really not clear what the context of your comment is...

@Trikaldarshi 2013-07-16 22:13:41

no not a problem i just added up to your comment that said "only one other constructor" so for many others create a long chain

@Harshit Gupta 2015-06-27 11:18:43

It is mandatory that if you are using this() or super() they must be the first statement of the constructor and both can not be used in a constructor.

@Francis 2015-06-28 16:01:40

@gsingh2011 yes, for some reason only a single constructor of a class is allowed.

@Jon Skeet 2015-06-28 16:32:05

@Francis: I assume you mean "you can only chain to one other constructor" - currently your statement makes it sound like you can only have one constructor per class, which is clearly not true.

@Francis 2015-06-29 11:06:40

@JonSkeet yup I meant chaining to one other constructor only. thanks for the correction and I apologize for my misleading statement.

@Justin Time 2016-02-09 18:50:46

@Francis I'm not sure, but I believe the reason is that if the first line of the constructor delegates to another constructor or calls a superclass constructor, it actually runs before the object is constructed. C++ has the same limit, you can only have one call to a parent class constructor or (as of C++11) one delegation per constructor, and no more, with both executing before the object is constructed.

@Jon Skeet 2016-02-09 18:52:39

@JustinTime: You'd have to define what you mean by "before the object is constructed" for me to be able to judge the truth of that...

@Justin Time 2016-02-09 18:59:21

@JonSkeet I mean that going from what I know of Java, delegation or superclass constructor calls are executed before the object's fields are initialised and it's put into a state where it's considered to be "constructed". Specifically, I believe the process is: 1) Run parent class/superclass constructor to initialise inherited portion of the class, 2) Initialise instance-specific member variables so the object is valid, so member access in the constructor's body won't break anything, 3) Execute body of constructor to finish construction. It's considered constructed by the end of step 3.

@Justin Time 2016-02-09 19:01:55

In that regard, I believe it works in the same manner as C++ (construct inherited portion, initialise object from initialisation list, run body of constructor), but with cleaner, but less specific, syntax (the initialisation list is moved to the top of the constructor's body, instead of being after the signature but before the body), with delegation passing the job of actually creating the object to the other constructor, and then running any code in the delegating constructor on a valid object after the constructor it delegates to returns. Correct me if I'm wrong.

@Jon Skeet 2016-02-09 19:06:42

@JustinTime: Again, it depends on what you mean by "creating" - the object is "created" in that its memory is allocated and the type is set before any constructor bodies are executed. Constructors are initialization rather than creation. In particular, the type of the object is its "final" type right from the start - so if you call any virtual methods from constructors, you'll get the most-specific override called. I believe this differs from C++.

@Justin Time 2016-02-09 19:15:04

By creating the object, I mean allocating memory, setting the type, and initialising fields, so that the object is in a valid, usable state (the implicit first step of every constructor), with delegation passing the job of making the object valid & usable onto the constructor that's delegated to. Didn't know that objects don't start as their actual type in C++, but it makes sense considering how C++ implicitly chains parent class constructor(s) to construct the inherited portion of a derived class before actually executing the derived class' constructor; I guess I'll have to be wary of that.

@amila isura 2015-05-26 15:09:17

Within a constructor, you can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.

Here's another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(1, 1);
    }
    public Rectangle(int width, int height) {
        this( 0,0,width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

}

This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.

@ANjaNA 2015-07-18 02:58:04

why don't you call second constructor which is Rectangle(int width, int height) in Rectangle() instead of Rectangle(int x, int y, int width, int height) ?

@Rodney P. Barbati 2018-05-29 16:21:01

A default constructor should not have knowledge of higher level constructors - it is the default. Following this pattern will result in you having to change one or more existing constructors when you add a new one. For example, add a lineWidth value and see what I mean. But have the default initialize all values, and reverse the constructor chain, you will see each constructor building on the prior, and initializing only the values which it specifically supports - You can add a new one without changing the existing ones. There are many common patterns in java that aren't good patterns.

@Wes 2018-10-23 12:30:55

@RodneyP.Barbati I can't agree in this case. That pattern doesn't allow for final fields.

@Christian Fries 2013-03-11 20:33:12

[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;

  }

}

@Engineer Dollery 2016-06-08 23:00:08

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.

@Christian Fries 2016-06-16 17:36:43

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).

@Rodney P. Barbati 2018-04-23 18:22:35

This is completely in reverse of what I would suggest - the no parameter constructor should initialize all values to defaults. The 2 parameter constructor should call the no param constructor, then initialize the 2 values it receives. The 3 parameter constructor should call the 2 parameter constructor, then initialize the 3rd value to the value it receives. Doing it as shown means you have to do a lot more work to add another parameter.

@Christian Fries 2018-06-13 06:06:33

@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).

@Christian Fries 2018-06-13 08:13:28

@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.

@John McClane 2018-07-29 01:34:10

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.

@ABHISHEK RANA 2015-11-27 19:01:24

You can a constructor from another constructor of same class by using "this" keyword. Example -

class This1
{
    This1()
    {
        this("Hello");
        System.out.println("Default constructor..");
    }
    This1(int a)
    {
        this();
        System.out.println("int as arg constructor.."); 
    }
    This1(String s)
    {
        System.out.println("string as arg constructor..");  
    }

    public static void main(String args[])
    {
        new This1(100);
    }
}

Output - string as arg constructor.. Default constructor.. int as arg constructor..

@olovb 2015-05-07 22:52:03

As everybody already have said, you use this(…), which is called an explicit constructor invocation.

However, keep in mind that within such an explicit constructor invocation statement you may not refer to

  • any instance variables or
  • any instance methods or
  • any inner classes declared in this class or any superclass, or
  • this or
  • super.

As stated in JLS (§8.8.7.1).

@Kaamel 2013-04-23 23:12:24

When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:

class MyClass {
   int field;


   MyClass() {
      init(0);
   } 
   MyClass(int value) {
      if (value<0) {
          init(0);
      } 
      else { 
          init(value);
      }
   }
   void init(int x) {
      field = x;
   }
}

But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example

class MyClass {
   int field;

   MyClass(int value) {
      if (value<0)
         field = 0;
      else
         field = value;
   }
   MyClass() {
      this(0);
   }
}

Related Questions

Sponsored Content

25 Answered Questions

79 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

64 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3787307 View
  • 3204 Score
  • 64 Answer
  • Tags:   java random integer

10 Answered Questions

[SOLVED] Calling the base constructor in C#

7 Answered Questions

[SOLVED] Iterate through a HashMap

8 Answered Questions

[SOLVED] Call one constructor from another

  • 2010-10-24 16:06:31
  • Avi
  • 401825 View
  • 868 Score
  • 8 Answer
  • Tags:   c# constructor

17 Answered Questions

[SOLVED] Virtual member call in a constructor

15 Answered Questions

[SOLVED] Can I call a constructor from another constructor (do constructor chaining) in C++?

  • 2008-11-21 09:43:08
  • Stormenet
  • 408716 View
  • 836 Score
  • 15 Answer
  • Tags:   c++ constructor

9 Answered Questions

[SOLVED] What are the rules for calling the superclass constructor?

Sponsored Content