Java Program to demonstrate constructor Overloading.
Objective
Write a Java program to demonstrate constructor overloading.
Algorithm / Approach
- Create a class
Rectanglewith fieldsl(length) andb(breadth). - Define a default (no-argument) constructor that sets
l = 5andb = 3. - Define a parameterized constructor that takes two integers and assigns them to the fields using the
thiskeyword. - Define an
area()method that prints the product oflandb. - In
main, instantiate twoRectangleobjects: one using the default constructor, and one using the parameterized constructor. - Call
area()on both objects.
Rectangle.java
class Rectangle {
int l, b;
Rectangle() {
l = 5;
b = 3;
}
Rectangle(int l, int b) {
this.l = l;
this.b = b;
}
void area() {
System.out.println("Area- "+(l*b));
}
}
class Main {
public static void main(String[] a)
{
Rectangle r =new Rectangle();
r.area();
Rectangle r2 = new Rectangle(20,10);
r2.area();
}
}
Expected Output
Area- 15 Area- 200
Explanation of the Program
- A constructor is a special method called automatically when an object is created. It is used to initialize the object.
- Constructor overloading means defining multiple constructors with the same name but different parameters.
- The
thiskeyword is used to distinguish between the class fields and the constructor arguments when they share the same name (e.g.,this.l = l).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Forgetting to use
this.when the parameter names match the instance variable names, which causes the parameter to just assign the value to itself (shadowing), leaving the object fields uninitialized.