Default constructor in java
In Java, a default constructor is a constructor that is automatically provided by the Java compiler if no other constructors are explicitly defined in a class. The default constructor has no arguments and is responsible for initializing the object's fields with default values.
Here are the characteristics of a default constructor:
1. No Arguments: A default constructor takes no arguments.
2. No Explicit Implementation: If you don't define any constructors in your class, Java will automatically generate a default constructor for you.
3. Initialization: The default constructor initializes instance variables to their default values based on their data types (e.g.,
0
for numeric types,null
for reference types, andfalse
for boolean).
Here's an example of a class with a default constructor:
In this example, the class MyClass
has two instance variables, number
and text
, and it also has a default constructor. When you create an object of this class without providing any constructor arguments, the default constructor is automatically invoked, and the fields are initialized with their default values.
package Tutorial_01;
public class MyClass {
int number;
String text;
public static void main(String[] args) {
// TODO Auto-generated method stub
// Instance variables
MyClass obj = new MyClass(); // Calls the default constructor
System.out.println(obj.number); // Outputs 0
System.out.println(obj.text); // Outputs null
}
}
It's important to note that once you define any constructor in a class (parameterized or no-arg constructor), the default constructor provided by Java is not automatically generated. Therefore, if you want to retain a no-arg constructor, you should explicitly define it yourself, like in the example above.