
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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(); } }