Hi This was the question asked in interview. Can we call one constructor from another if a class has multiple constructors in java and when?How can I call I mean syntax?
example:
public class FileDb {
/**
*
*/
public FileDb() {
this(null);
}
public FileDb(String filename) {
// ...
}
}
You can, and the syntax I know is
this(< argument list >);
You can also call a super class' constructor through
super(< argument list >);
Both such calls can only be done as the first statement in the constructor (so you can only call one other constructor, and before anything else is done).
Yes, you can do that.
Have a look at the 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 calls the first one with a default capacity
of ten.
FYI, this is called the telescoping/telescopic constructor pattern.
It's discussed 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.
None of the answers are complete, so I'm adding this one to fill in the blanks.
You can call one constructor from another in the same class, or call the super class, with the following restrictions:
- It has to be the first line of code in the calling constructor.
- 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 mentioned by others) is:
MyClass() {
someInitialization();
}
MyClass(String s) {
this();
doSomethingWithS(s);
}