- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Are Multiple Constructors possible 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(); } }
- Related Articles
- What are constructors in Java?
- What are Default Constructors in Java?
- What are copy constructors in Java?
- What are parametrized constructors in Java?
- Constructors in Java\n
- How many types of constructors are there in Java?
- Get all Constructors in Java
- Type of Java constructors
- Can interfaces have constructors in Java?
- Can constructors be inherited in Java?
- Constructors of StringBuffer class in Java.
- Constructors of StringBuilder class in Java.
- Constructors of StringTokenizer class in Java.
- Are the constructors in an object invoked when de-serialized in Java?
- Java Interview Questions on Constructors
