Is it possible to call one constructor from another in Java?
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)?
Yes, it is definitely possible to call a constructor within the same class:
It's a common technique, e.g. for constructor chaining:
Since we can create multiple constructors of the same class by changing the method signature. We can call one constructor from another constructor using the this(). If the other constructor accepts an integer value than we can call it by saying this(5) etc. Always remember that this() should be the first line inside the constructor.
There are two types of constructors:
I will explain in one Example
ConstructorDemo(int k)//Parameterized constructor
public static void main(String args)
//this(); error because "must be first statement in constructor
ConstructorDemo g=new ConstructorDemo(3);---(3)
In the above example I showed 3 types of calling
this() call to this must be first statement in constructor
This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.
Note: this must be the first statement in the constructor
~ swim ~
It was like a deja vu. if not the URL is helpful - gathering as much information as possible from different sources about your targeted programing language is a great way to learn.
- practice : Clean code
- theory : text = selling
Thewbsite = text
Yes it's possible to call a constructor from another constuctor. I will extend all methods from parent constructor to child constructor and by using this() function we can access the value from parent constructor.
Java constructor chaining is a method of calling one constructor with the help of another while considering the present object.
It can be done in 2 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 a constructor from the base class