Default Constructor in Java
Sent by Copilot:
In Java, a default constructor is a constructor that is automatically generated by the compiler if no constructors are explicitly defined in a class. It is a no-argument constructor that initializes the object with default values.
What Does the Default Constructor Do?
Initialization: The default constructor initializes the object with default values. For primitive data types, these default values are:
int
,short
,byte
,long
:0
float
,double
:0.0
char
:'\u0000'
(null character)boolean
:false
- For reference types (like objects), the default value is
null
.
Implicit Creation: If you do not define any constructor in your class, the Java compiler automatically provides a default constructor.
Example
Let’s look at an example to understand this better:
Java
class Student {
String name;
int age;
// No explicit constructor defined
}
public class Main {
public static void main(String[] args) {
Student student = new Student(); // Default constructor is called
System.out.println("Name: " + student.name); // Output: Name: null
System.out.println("Age: " + student.age); // Output: Age: 0
}
}
Explanation:
- Class Definition: The
Student
class does not have any explicitly defined constructors. - Object Creation: When we create an object of the
Student
class usingnew Student()
, the default constructor is called. - Default Values: The
name
attribute is aString
, so its default value isnull
. Theage
attribute is anint
, so its default value is0
.
Comments
Post a Comment