I want to call default constructor from a parameterized constructor inside a public java class.
Can I achieve it?
Compiler will not call default constructor(zero argument constructor), if we define parameterized constructor explicitly. Thus creating class object without parameters gives compile time error.
Actually you can't do that in Java, by definition. JLS §8.8.
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”.
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.
Use this();
in the first line of the parametrized constructor and it will call your default constructor. Make sure you have default constructor as compiler will not provide one if you declare a parametrized constructor.
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