Multiple Constructors in Java



There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.

A program that demonstrates this is given as follows −

Example

 Live Demo

class NumberValue {
   private int num;
   public NumberValue() {
      num = 6;
   }
   public NumberValue(int n) {
      num = n;
   }
   public void display() {
      System.out.println("The number is: " + num);
   }
}
public class Demo {
   public static void main(String[] args) {
      NumberValue obj1 = new NumberValue();
      NumberValue obj2 = new NumberValue(15);
      obj1.display();
      obj2.display();
   }
}

Output

The number is: 6
The number is: 15

Now let us understand the above program.

The NumberValue class is created with a data member num and single member function display() that displays the value of num. There are two constructors in class NumberValue where one of these takes no parameters and the other takes a single parameter of type int. A code snippet which demonstrates this is as follows −

class NumberValue {
   private int num;
   public NumberValue() {
      num = 6;
   }
   public NumberValue(int n) {
      num = n;
   }
   public void display() {
      System.out.println("The number is: " + num);
   }
}

In the main() method, objects obj1 and obj2 of class NumberValue are created and the display() method is called for both of them. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      NumberValue obj1 = new NumberValue();
      NumberValue obj2 = new NumberValue(15);
      obj1.display();
      obj2.display();
   }
}
Updated on: 2020-06-30T08:45:40+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements