Home > DeveloperSection > Forums > How do I call one constructor from another in Java?
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    May-12-2015 1:51 AM

 Java Java 
Ratings:


 1 Reply(s)
 568  View(s)
Rate this:
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)?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-12-2015 6:50 AM

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.

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

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. There is also a "static"version of this to initialize static members: "static { ... }"



Don't want to miss updates? Please click the below button!

Follow MindStick