Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Constructor Overloading

It is very much similar to method overloading.
When a class contains two or more constructors with different types, numbers & sequence of parameters, it is known as constructor overloading.
And the constructors are called overloaded constructors.
Java invokes the correct constructor among overloaded constructors by checking the number, type & sequence of the parameters. That is, the constructor whose parameters matches with the arguments passed during object creation is invoked.

Example

public class Car 
{
    String name;
    String color;
    int gears;
    boolean isAutoGear;
	
    Car()
    {
        name = "BMW-720";
        color = "Black";
        gears = 7;
        isAutoGear = true;
    }
	
    Car(String name, String color, int gears, boolean isAutoGear)
    {
        this.name = name;
        this.color = color;
        this.gears = gears;
        this.isAutoGear = isAutoGear;
    }
	
    Car(String name)
    {
        this.name = name;
        color = "Red";
        gears = 5;
        isAutoGear = false;
    }
	
    Car(String name,boolean isAutoGear)
    {
        this.name = name;
        color = "white";
        gears = 4;
        this.isAutoGear = isAutoGear;
    }
	
    public void display()
    {
        System.out.println(name);
        System.out.println(color);
        System.out.println(gears);
        System.out.println(isAutoGear);
        System.out.println("------------------");
    }
	
    public static void main(String args[])
    {
        Car c1 = new Car();
        Car c2 = new Car("Skoda");
        Car c3 = new Car("Swift", true);
        Car c4 = new Car("Ferrari", "Yellow", 7, true);
		
        c1.display();
        c2.display();
        c3.display();
        c4.display();
    }
}

Output

BMW-720
Black
7
true
------------------
Skoda
Red
5
false
------------------
Swift
white
4
true
------------------
Ferrari
Yellow
7
true
------------------

For a better understanding of the above program look at the diagram shown below:

Java Programming Language Constructor Overloading Working
 

Leave a reply