DEV Community

Anees Abdul
Anees Abdul

Posted on

Constructors in Java:

What is Constructor:

*It is a block of code that is used to initialize an object.
*It runs automatically when we create an object; the constructor of that class will be invoked immediately.

Why is a constructor needed:

  • When an object is created, memory is allocated for it. Constructor helps in assigning initial values to the variables of that object at the time of creation.

Characteristics of a Constructor:

  • Constructor name must be the same as the class name
  • It does not have a return type (not even void)
  • It invoked automatically and mainly used of object initialization
  • It can be overloaded(multiple constructors in a class)

Example:

    class Person {
    String name;
    int age;

    // This is a constructor
        Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Using the constructor:
Person john = new Person("John", 25);
Enter fullscreen mode Exit fullscreen mode

When you write new Person("John", 25), Java calls the constructor and sets up the object with those values.

Types of Constructors:

  1. Default Constructor (No-argument constructor)
  2. Parameterized Constructor

1.1 What is a Default Constructor:
*It is a constructor without Parameters.If you don't write a constructor, Java automatically provides one.

 class Dog {
    String name;

    // Java automatically creates this if you don't write any constructor:
    // public Dog() { }
}

Dog myDog = new Dog(); // Uses default constructor
Enter fullscreen mode Exit fullscreen mode

2.1 What is a Parameterized Constructor:
*A constructor that takes parameters to initialize the object with specific values.

class Dog {
    String name;
    int age;

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

Dog myDog = new Dog("Buddy", 3); // Passes values during creation
Enter fullscreen mode Exit fullscreen mode

What is a This Keyword:
this is a reference to the current object

class Student {
    String name;  // This is a field
    int age;      // This is a field

    public Student(String name, int age) {
        this.name = name;  // this.name = field, name = parameter
        this.age = age;    // this.age = field, age = parameter
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
francistrdev profile image
๐Ÿ‘พ FrancisTRDev ๐Ÿ‘พ

Great overview of Constructors and why is needed. Great job!