Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call default constructor from parameterized constructor inside public class in java?

Tags:

java

I want to call default constructor from a parameterized constructor inside a public java class.

Can I achieve it?

like image 797
psisodia Avatar asked Oct 12 '12 05:10

psisodia


People also ask

Is default constructor called when parameterized constructor is called?

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.

Can we have both default constructor and parameterized constructor in the same class in Java?

Actually you can't do that in Java, by definition. JLS §8.8.

How do you call a default constructor from another constructor in Java?

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 you call a constructor of a class inside another constructor?

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.


1 Answers

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.

like image 63
Abubakkar Avatar answered Oct 06 '22 01:10

Abubakkar