CONSTRUCTOR – Overloading

Java allows having more than one constructor inside one Class.In Constructor overloading you have multiple constructors with a different signature. The biggest advantage of Constructor overloading is flexibility which allows you to create the object in a different way

for function/method overloading see – Compile time polymorphism (static binding)

// Java program to illustrate Constructor Overloading 
class Box 
{ 
	double width, height, depth; 
	// constructor used when all dimensions 
	Box(double w, double h, double d) 
	{ 
		width = w; 
		height = h; 
	depth = d; 
	} 
	// constructor used when no dimensions 
	Box() 
	{ 
		width = height = depth = 0; 
	} 
	// constructor used when cube is created 
	Box(double len) 
	{ 
		width = height = depth = len; 
	} 
} 
public class Test 
{
	public static void main(String args[]) 
	{ 
	// create boxes using the various constructors 
	Box mybox1 = new Box(10, 20, 15); 
	Box mybox2 = new Box();
	Box mycube = new Box(7);
	} 
} 
This entry was posted in Basic. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *