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?
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.
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”.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With