What is a Constructor and Explain the advantage of contructors overloading with an example of a java program?

Answer:
Constructors are used to create objects of a particular Class.

Overloaded Constructors

Overloading a constructor means typing in multiple versions of the constructor, each having a different argument list, like the following examples:

class Car {
Car() { }
Car(String s) { }
}

The preceding Car class has two overloaded constructors, one that takes a string, and one with no arguments. Because there's no code in the no-arg version, it's actually identical to the default constructor the compiler supplies, but remember-since there's already a constructor in this class (the one that takes a string), the compiler won't supply a default constructor. If you want a no-arg constructor to overload the with-args version you already have, you're going to have to type it yourself, just as in the Car example.

Overloading a constructor is typically used to provide alternate ways for clients to instantiate objects of your class. For example, if a client knows the Car name, they can pass that to a Car constructor that takes a string. But if they don't know the name, the client can call the no-arg constructor and that constructor can supply a default name. Here's what it looks like:

1. public class Car {
2. String name;
3. Car(String name) {
4. this.name = name;
5. }
6.
7. Car() {
8. this(makeRandomName());
9. }
10.
11. static String makeRandomName() {
12. int x = (int) (Math.random() * 5);
13. String name = new String[] {"Ferrari", "Lamborghini",
"Rover", "Spyker",
"Lotus"}[x];
14. return name;
15. }
16.
17. public static void main (String [] args) {
18. Car a = new Car();
19. System.out.println(a.name);
20. Car b = new Car("Proton");
21. System.out.println(b.name);
22. }
23. }

Running the code four times produces this output:

% java Car
Lotus
Proton

% java Car
Ferrari
Proton

% java Car
Rover
Proton

% java Car
Ferrari
Proton
First answer by Anandvijayakumar. Last edit by Anandvijayakumar. Contributor trust: 782 [recommend contributor recommended]. Question popularity: 1 [recommend question].