Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
Is it possible to overload constructors?

1 Answer

0 votes
by (11.3k points)

Yes, we can. In the exact same way as a method or function. We can achieve this by differentiating overloaded constructors on the basis of the number of parameters and data types of those parameters which accept the arguments. 

Refer to the following code:

class hello {

public hello() { 

System.out.println("1 called.");

}

public hello(int a) {

System.out.println("2 called.");

}

public static void main(String arg[]){

hello ob1=new hello();

hello ob2=new hello(2);

}

}

/* Output:

1 called.

2 called.

*/

As we can see, both the constructors are being called and the overloading works as the output for the code clearly says that upon no arguments being passed, the first constructor is called and "1 called." is printed and upon creating an object with passing an integer parameter, it matches the signature of the second constructor and "2 called." is printed. I hope that makes things clearer for you in terms of understanding than constructors almost work in an identical fashion to methods. 

Learn more from this Java Tutorial.

Related questions

0 votes
1 answer
asked Jan 27, 2020 in Java by angadmishra (6.5k points)
0 votes
1 answer
0 votes
1 answer
asked Feb 18, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 15, 2021 in Java by Jake (7k points)

Browse Categories

...