Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate constructor Overloading.

Java Code Example — OOP Programs

ADVERTISEMENT

Java Program to demonstrate constructor Overloading.

Objective

Write a Java program to demonstrate constructor overloading.

Algorithm / Approach

  1. Create a class Rectangle with fields l (length) and b (breadth).
  2. Define a default (no-argument) constructor that sets l = 5 and b = 3.
  3. Define a parameterized constructor that takes two integers and assigns them to the fields using the this keyword.
  4. Define an area() method that prints the product of l and b.
  5. In main, instantiate two Rectangle objects: one using the default constructor, and one using the parameterized constructor.
  6. 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 this keyword 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.
ADVERTISEMENT