Default or no-argument constructor
A constructor which does not have any parameter is called default or no-argument constructor. If no constructor is available within the class then java compiler automatically or robotically creates a default constructor on the time of compilation.
Syntax:
ClassName(){ //Block of statements (Optional) }
Why default constructor is used?
Default constructor is used to provide default values to the object properties i.e. to provide default state of an object.
Example
/** * This program is used to show the use of default constructor. * @author w3schools */ public class DefaultConstructor { String dataMember1; int dataMember2; DefaultConstructor (){ System.out.println("Default Constructor called."); } public static void main(String args[]){ //constructor call DefaultConstructor obj1 = new DefaultConstructor(); //print default values of object properties. System.out.println("dataMember1= " + obj1.dataMember1); System.out.println("dataMember2= " + obj1.dataMember2); } } |
Output
Default Constructor called. dataMember1= null dataMember2= 0 |
Java interview questions on constructor
- Default constructor
- Does constructor return any value in java?
- Is constructor inherited in java?
- Can you make a constructor final in java?
- Difference between constructor and method in java?
- How to copy values from one object to another java?
- How to overload constructor in java?
- can you create an object without using new operator in java?
- Constructor chaining in java
- Parameterized constructor in java
- Can we call subclass constructor from superclass constructor?
- What happens if you keep return type for a constructor?
- What is the use of private constructor in java?
- Can a constructor call another constructor java?