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?

  1. Initialization: The default constructor initializes the object with default values. For primitive data types, these default values are:

    • intshortbytelong0
    • floatdouble0.0
    • char'\u0000' (null character)
    • booleanfalse
    • For reference types (like objects), the default value is null.
  2. 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 using new Student(), the default constructor is called.
  • Default Values: The name attribute is a String, so its default value is null. The age attribute is an int, so its default value is 0.

Comments

Popular posts from this blog

Jenkins CICD in One Page

Why do we need a build tool?

Deutsche Bank Interview Questions - 2024