DEV Community

Arun
Arun

Posted on

CONSTRUCTOR IN OOPS

In OOPs (Object-Oriented Programming System), a constructor is a special method that is automatically called when an object of a class is created.

👉 It is mainly used to initialize objects (assign values to variables when the object is created).

Key Points about Constructor:

  1. Name same as class → A constructor must have the same name as the class.

  2. No return type → Not even void.

  3. Called automatically → Executes when an object is created using new.

  4. Used for initialization → Sets initial values for object variables.

Program
class Student {
int age;
String name;

// Constructor
Student(int a, String n) {
    age = a;
    name = n;
}

void display() {
    System.out.println("Name: " + name + ", Age: " + age);
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
// Object creation calls constructor
Student s1 = new Student(20, "Arun");
Student s2 = new Student(22, "Kumar");

    s1.display();
    s2.display();
}
Enter fullscreen mode Exit fullscreen mode

}
Output
Name: Arun, Age: 20
Name: Kumar, Age: 22

Why we need constructors in OOPs?

  1. Automatic Initialization

When you create an object, its variables get values immediately without calling any extra method.

Student s = new Student(20, "Arun"); // values set automatically

  1. Code Simplicity

Without constructors, you would write a method like setData() and call it manually after creating the object.

Constructors remove this extra step.

  1. Encapsulation Support

They help keep variables private and still allow controlled initialization.

  1. Different Ways of Object Creation

With overloaded constructors (same name, different parameters), we can create objects in different ways.

Student s1 = new Student(); // default constructor
Student s2 = new Student(20, "Arun"); // parameterized constructor

  1. Readability & Maintainability Code becomes more organized because initialization is tied to object creation.

Example without constructor
class Student {
int age;
String name;

void setData(int a, String n) {
    age = a;
    name = n;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setData(20, "Arun"); // must call method separately
}
}

Example With Constructor

class Student {
int age;
String name;

Student(int a, String n) {
    age = a;
    name = n;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
Student s = new Student(20, "Arun"); // initialized automatically
}
}

Top comments (0)