Constructor Overloading in Java

Jul 30, 2024

Constructor Overloading

Information about Constructor

  • The constructor name is the same as the class name.
  • The default constructor has no arguments.
  • The constructor is called when the class object is created.

What is Constructor Overloading?

  • Constructor overloading means having more than one constructor in the same class.
  • Each constructor should have a different signature (parameters) to prevent compile-time errors.

Example

  1. Default Constructor
    public Program() {
        System.out.println("This is the first constructor");
    }
    
  2. Constructor with Two Arguments
    public Program(int a, int b) {
        System.out.println(a + b);
    }
    
  3. Constructor with Three Arguments
    public Program(int a, int b, int c) {
        System.out.println(a + b + c);
    }
    
  4. Constructor with String Arguments
    public Program(String a, String b, String c) {
        System.out.println(a + b + c);
    }
    

Calling Constructor While Creating Object

  • Calling Default Constructor
    Program p = new Program();
    
    • Output: This is the first constructor
  • Calling Constructor with Two Arguments
    Program p = new Program(20, 30);
    
    • Output: 50
  • Calling Constructor with Three Arguments
    Program p = new Program(20, 30, 20);
    
    • Output: 70
  • Calling Constructor with String Arguments
    Program p = new Program("a", "b", "c");
    
    • Output: abc

Key Points

  • In constructor overloading, all constructors must have a different signature.
  • The correct constructor is chosen at compile-time based on the arguments.
  • An error will occur if you create constructors with the same signature.