- 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
What are Default Constructors in Java?
The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.
A program that demonstrates this is given as follows:
Example
class NumberValue { private int num; public void display() { System.out.println("The number is: " + num); } } public class Demo { public static void main(String[] args) { NumberValue obj = new NumberValue(); obj.display(); } }
Output
The number is: 0
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. A code snippet which demonstrates this is as follows:
class NumberValue { private int num; public void display() { System.out.println("The number is: " + num); } }
In the main() method, an object obj of class NumberValue is created and the default constructor is called. Then display() method is called. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { NumberValue obj = new NumberValue(); obj.display(); } }
Advertisements