0 votes
1 view
in Java by (2.4k points)

1 Answer

0 votes
by (5.4k 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. 

Related questions

0 votes
1 answer
asked Jan 27 in Java by angadmishra (2.4k points)
0 votes
1 answer
0 votes
1 answer
asked Jan 23 in Java by angadmishra (2.4k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...