Java - Constructor Overloading
Like Methods, a constructors can also be overloaded in Java. With constructor overloading feature in Java, two or more constructors can be created in the same class with different definitions like different number and types of parameters. The compiler automatically calls the constructor which matches the argument passed while creating the object.
Example:
In this example two constructors are created. The first constructor (default constructor) takes no parameters and the second constructor takes one parameter to initialize an object of the class Circle.
In the main method, two objects of class Circle are created: Cir1 and Cir2. Cir1 uses default constructor to initialize the object while the Cir2 uses the constructor that takes one parameter to initialize the object.
public class Circle { //class attribute int radius; //class constructor without parameter public Circle() { radius = 1; } //class constructor with one parameter public Circle(int x) { radius = x; } //class method public double area() { return 22/7.0*radius*radius; } public static void main(String[] args) { Circle Cir1 = new Circle(); Circle Cir2 = new Circle(10); System.out.println(Cir1.area()); System.out.println(Cir2.area()); } }
The output of the above code will be:
3.142857142857143 314.2857142857143
Note: A constructor is called default constructor, if it takes no arguments to initialize the object.