views:

5402

answers:

2

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

+22  A: 

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.

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

Jon Skeet
Wow! That was quick and easy. Thanks Jon and thanks everybody. Let me click on that 'accepted answer' thing.
askgelal
+8  A: 

Using this(args).

The best way is from the smallest constructor to the largest.

public class Cons {
 public Cons() {
  this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
 }
 public Cons(int arg1, int arg2) {
  this(arg1,arg2, madeUpArg3Value);
 }


 public Cons(int arg1, int arg2, int arg3) {
  // Largest constructor that does the work
  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(asdf). Note that it must be the first call in the constructor.

Josh