[ACCEPTED]-call one constructor from another in java-constructor

Accepted answer
Score: 42

You can, and the syntax I know is

this(< argument list >);

You can 5 also call a super class' constructor through 4

super(< argument list >);

Both such calls can only be done as the 3 first statement in the constructor (so you 2 can only call one other constructor, and 1 before anything else is done).

Score: 11

Yes, you can do that.

Have a look at the 2 ArrayList implementation for example:

public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
}

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this(10);
}

The second constructor 1 calls the first one with a default capacity of ten.

Score: 10

None of the answers are complete, so I'm 5 adding this one to fill in the blanks.

You 4 can call one constructor from another in 3 the same class, or call the super class, with 2 the following restrictions:

  1. It has to be the first line of code in the calling constructor.
  2. It cannot have any explicit or implicit reference to this. So you cannot pass an inner class (even an anonymous one if it references any instance methods), or the result of a non-static method call, as a parameter.

The syntax (as 1 mentioned by others) is:

MyClass() {
   someInitialization();
}

MyClass(String s) { 
     this();
     doSomethingWithS(s);
}
Score: 8

FYI, this is called the telescoping/telescopic constructor pattern.

It's discussed 1 in JLS 8.8.7.1 Explicit Constructor Invokations

  • Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.
  • Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary expression. They are used to invoke a constructor of the direct superclass.
Score: 7
this(other, args);

0

Score: 6

example:

public class FileDb {

  /**
   * 
   */
  public FileDb() {
    this(null);
  }

  public FileDb(String filename) {
    // ...
  }

}

0

More Related questions