Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Constructor in JAVA

  • In Java, a constructor is a special method used to initialize objects of a class.
  • It is called automatically when an object is created using the new keyword.
  • Constructors have the same name as the class and do not have a return type, not even void.
  • They are primarily used to set initial values to the instance variables of an object.

Here are some key points about constructors in Java:

1. Purpose:

  • Constructors initialize the state of an object.
  • They allocate memory for the object and set its initial values.
  • Constructors are used to ensure that an object is properly initialized before it is used.

2. Syntax:

  • A constructor has the same name as the class it belongs to.
  • It does not have a return type, not even void.
  • Constructors can have parameters (parameterized constructor) or no parameters (default constructor).

Example:

Java
public class MyClass {
    // Default constructor
    public MyClass() {
        // Constructor body
    }

    // Parameterized constructor
    public MyClass(int value) {
        // Constructor body
    }
}

3. Default Constructor:

  • If a class does not have any explicitly defined constructors, it automatically has a default constructor.
  • The default constructor takes no parameters and provides a default initialization for the instance variables.

Example:

Java
public class Person {
    private String name;
    private int age;

    // Default constructor
    public Person() {
        name = "";
        age = 0;
    }
}

4. Parameterized Constructor:

  • A parameterized constructor takes one or more parameters to initialize the instance variables of an object.
  • It allows values to be passed to the constructor at the time of object creation.

Example:

Java
public class Student {
    private String name;
    private int age;

    // Parameterized constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

5. Constructor Overloading:

  • Like regular methods, constructors can be overloaded by defining multiple constructors with different parameter lists.
  • This allows objects to be created with different initialization options.

Example:

Java
public class Rectangle {
    private int width;
    private int height;

    // Constructor with no parameters
    public Rectangle() {
        width = 0;
        height = 0;
    }

    // Constructor with two parameters
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

Constructors play a crucial role in object initialization and ensure that objects are properly initialized with appropriate values. They provide a way to customize the initialization process based on the requirements of the class.