Java - Class Constructor Overloading

What is Constructor Overloading?

A class can have more than one constructor, which are called overloaded constructors.

Syntax

If a class has multiple constructors, all of them must differ from the others in the number, order, or type of parameters.

Example

A Dog Class with Two Constructors, One with No Parameter and One with a String Parameter.

class Dog {
  // Constructor #1
  public Dog() {
    System.out.println("A dog is created.");
  }

  // Constructor #2
  public Dog(String name) {
    System.out.println("A dog named " + name + " is created.");
  }
}

You can use any of them to create an object of that class.

Dog dog1 = new Dog();
Dog dog2 = new Dog("Cute");

The first statement uses the constructor with no parameters.

The second one uses the constructor with a String parameter.

Demo

class Dog {
  // Constructor #1
  public Dog() {/*from w w  w  . j  a  v  a 2 s  .c  o  m*/
    System.out.println("A dog is created.");
  }

  // Constructor #2
  public Dog(String name) {
    System.out.println("A dog named " + name + " is created.");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog d1 = new Dog(); // Uses Constructor #1
    Dog d2 = new Dog("Cute"); // Uses Constructor #2
  }
}

Result

Related Topic