Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call one constructor from another in java [duplicate]

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?

like image 524
giri Avatar asked Mar 03 '10 18:03

giri


People also ask

Can I call constructor from another constructor Java?

The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.

Can I make call from one constructor to another constructor?

To call one constructor from another constructor is called constructor chaining in java. This process can be implemented in two ways: Using this() keyword to call the current class constructor within the “same class”. Using super() keyword to call the superclass constructor from the “base class”.

Can we call constructor twice in Java?

No, there is no way to do this. Even at the JVM bytecode level, a chain of <init> methods (constructors) can be called at most once on any given object.

How can call the constructor from another constructor in a same class?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.


2 Answers

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

like image 59
Sean Avatar answered Oct 02 '22 11:10

Sean


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.

like image 41
Peter Lang Avatar answered Oct 02 '22 11:10

Peter Lang