Constructor Overloading in Java

In java Constructor can also be overloaded like methods overloading. We can create as many constructors with different arguments.Constructor can be of default without any parameter or parameterized constructor.

While we define parameterized constructor compiler will not define default constructor at compile time.If no any default constructor found then compiler generates an error while creating objects using default constructor.

Here I am taking example to overload constructors for Product class.

Product.java


package com.startwithjava;
public class Product {
private int id;
private String name;
private double price;
public Product(){
this.id = id;
this.name = name;
this.price = 0;
}
public Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public Product(int id,String name){
this.id = id;
this.name = name;
this.price = 0;
}
public void display(){
System.out.println("Id:"+id+"\tName:"+name+"\tPrice:"+price);
}

}

ConstructorOverloading.java


public class ConstructorOverloading {

public static void main(String args[]){

//Default Constructor
System.out.println("Using Default Constructor");
Product p = new Product();
p.display();

//Parameterized Constructor

System.out.println("\nUsing Parameterized Constructor");

Product p2 = new Product(100,"A",5000);
p2.display();

}
}

Output

Using Default Constructor
Id:0    Name:null    Price0.0

Using Parameterized Constructor
Id:100    Name:A    Price5000.0

 

Leave a Reply