DEV Community

Madhavan G
Madhavan G

Posted on

Understanding Constructors in Java: Why We Need Them and How They Solve Object Creation Problems.

This is the program we worked in the last blog

Program Without a Constructor

public class Building {

    static int age = 10;
    static String name = "Payilagam";

    String studName1 = "Mohan";
    int studAge1 = 22;

    String studName2 = "Deva";
    int studAge2 = 23;

    String studName3 = "Madhavan";
    int studAge3 = 24;

    public static void main(String[] args) {

        Building student1 = new Building();
        Building student2 = new Building();
        Building student3 = new Building();

        System.out.println(Building.name);
        System.out.println(Building.age);

        System.out.println(student1.studName1 + " " + student1.studAge1);
        System.out.println(student1.studName2 + " " + student1.studAge2);
        System.out.println(student1.studName3 + " " + student1.studAge3);
    }
}
Enter fullscreen mode Exit fullscreen mode

What Is the Problem with This Program?

At first glance, the program seems to work correctly. It prints:

Payilagam
10
Mohan 22
Deva 23
Madhavan 24
Enter fullscreen mode Exit fullscreen mode

However, if we carefully examine the class, we can identify several design problems.

Problem 1: One Object Contains Data for Multiple Students

Notice these instance variables:

String studName1 = "Mohan";
int studAge1 = 22;

String studName2 = "Deva";
int studAge2 = 23;

String studName3 = "Madhavan";
int studAge3 = 24;
Enter fullscreen mode Exit fullscreen mode

Instead of representing one student, a single Building object stores the details of three different students.

This defeats the purpose of object-oriented programming.

Ideally,

  • student1 should represent only Mohan.
  • student2 should represent only Deva.
  • student3 should represent only Madhavan.

Instead, every object contains all three students.


Problem 2: Every Object Stores the Same Data

Consider these statements:

Building student1 = new Building();
Building student2 = new Building();
Building student3 = new Building();
Enter fullscreen mode Exit fullscreen mode

You might expect each object to have different information.

But all three objects actually contain exactly the same values.

For example,

student1 contains

studName1 = Mohan
studName2 = Deva
studName3 = Madhavan
Enter fullscreen mode Exit fullscreen mode

Similarly,

student2 also contains

studName1 = Mohan
studName2 = Deva
studName3 = Madhavan
Enter fullscreen mode Exit fullscreen mode

And the same is true for student3.

Creating multiple objects serves no purpose because every object is identical.


Problem 3: Not Scalable

Imagine storing details for 100 students.

You would have to write

String studName1;
String studName2;
String studName3;
...
String studName100;
Enter fullscreen mode Exit fullscreen mode

and

int studAge1;
int studAge2;
int studAge3;
...
int studAge100;
Enter fullscreen mode Exit fullscreen mode

This results in hundreds of variables, making the program difficult to read, maintain, and extend.


Problem 4: Objects Cannot Store Unique Data

Suppose you want to add a new student named Akash.

You would need to modify the class itself by adding new variables:

String studName4 = "Akash";
int studAge4 = 25;
Enter fullscreen mode Exit fullscreen mode

Every time a new student is added, the class must be edited.

A well-designed class should not require modification whenever new objects are created.

To solve this we are using constructor.


What is a Constructor?

A constructor is a special member of a class that is automatically executed whenever an object is created.

Unlike ordinary methods, constructors are not called manually. Java automatically invokes them whenever an object is created using the new keyword.

A constructor has the following characteristics:

*It has the same name as the class.
*It does not have a return type, not even void.
*It executes automatically when an object is created.
*It is mainly used to initialize instance variables.

How Constructors Solve These Problems

Instead of creating separate variables for every student, we create only one name variable and one age variable.

String studName;
int studAge;
Enter fullscreen mode Exit fullscreen mode

Now each object stores its own values.

To initialize these variables automatically, we use a constructor.

Program Using a Constructor

public class Building {

    static int age = 10;
    static String name = "Payilagam";

    String studName;
    int studAge;

    // Constructor
    public Building(String studName, int studAge) {
        this.studName = studName;
        this.studAge = studAge;
    }

    public void display() {
        System.out.println(studName + " " + studAge);
    }

    public static void main(String[] args) {

        Building student1 = new Building("Mohan", 22);
        Building student2 = new Building("Deva", 23);
        Building student3 = new Building("Madhavan", 24);

        System.out.println(Building.name);
        System.out.println(Building.age);

        student1.display();
        student2.display();
        student3.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Program Using a Constructor screenshot:


How the Constructor Fixes the Problem

The constructor is

public Building(String studName, int studAge) {
    this.studName = studName;
    this.studAge = studAge;
}
Enter fullscreen mode Exit fullscreen mode

Whenever an object is created, Java automatically passes the supplied values to the constructor.

For example,

Building student1 = new Building("Mohan", 22);
Enter fullscreen mode Exit fullscreen mode

Java internally executes

this.studName = "Mohan";
this.studAge = 22;
Enter fullscreen mode Exit fullscreen mode

Similarly,

Building student2 = new Building("Deva", 23);
Enter fullscreen mode Exit fullscreen mode

stores

studName = Deva
studAge = 23
Enter fullscreen mode Exit fullscreen mode

Each object now has its own unique data.


Understanding the Constructor

The constructor accepts two parameters.

public Building(String studName, int studAge)
Enter fullscreen mode Exit fullscreen mode

Whenever Java creates an object, it automatically passes the supplied values to these parameters.

Inside the constructor,

this.studName = studName;
this.studAge = studAge;
Enter fullscreen mode Exit fullscreen mode

the values received through the parameters are stored in the object's instance variables.

This ensures that every object is initialized immediately after creation.


What Does the this Keyword Mean?

Many beginners get confused by this line:

this.studName = studName;
Enter fullscreen mode Exit fullscreen mode

Both variables have the same name, but they represent different things.

studName refers to the constructor parameter.
this.studName refers to the instance variable of the current object.

Therefore,

this.studName = studName;
Enter fullscreen mode Exit fullscreen mode

means:

Store the value passed to the constructor inside the current object's studName variable.

Similarly,

this.studAge = studAge;
Enter fullscreen mode Exit fullscreen mode

stores the age passed by the user inside the object's studAge variable.

The this keyword helps Java distinguish between instance variables and constructor parameters when they have the same name.


How Object Creation Works

Consider the following statement:

Building student1 = new Building("Mohan", 22);
Enter fullscreen mode Exit fullscreen mode

When Java executes this line, two important things happen automatically.

Step 1: Memory Allocation

Java allocates memory for a new Building object.

Step 2: Constructor Execution

Immediately after creating the object, Java calls

Building("Mohan", 22)
Enter fullscreen mode Exit fullscreen mode

Inside the constructor,

this.studName = "Mohan";
this.studAge = 22;
Enter fullscreen mode Exit fullscreen mode

Now the object contains:

studName = Mohan
studAge = 22
Enter fullscreen mode Exit fullscreen mode

The same process happens for every object.

When Java executes

Building student2 = new Building("Deva", 23);
Enter fullscreen mode Exit fullscreen mode

the constructor initializes

studName = Deva
studAge = 23
Enter fullscreen mode Exit fullscreen mode

Similarly,

Building student3 = new Building("Madhavan", 24);
Enter fullscreen mode Exit fullscreen mode

creates another object containing

studName = Madhavan
studAge = 24
Enter fullscreen mode Exit fullscreen mode

Although all three objects are created from the same class, each object stores different values.


Understanding the display() Method

The display() method prints the instance variables of the object that calls it.

public void display() {
    System.out.println(studName + " " + studAge);
}
Enter fullscreen mode Exit fullscreen mode

When

student1.display();
Enter fullscreen mode Exit fullscreen mode

is executed, the output is

Mohan 22
Enter fullscreen mode Exit fullscreen mode

When

student2.display();
Enter fullscreen mode Exit fullscreen mode

is executed, the output becomes

Deva 23
Enter fullscreen mode Exit fullscreen mode

Similarly,

student3.display();
Enter fullscreen mode Exit fullscreen mode

prints

Madhavan 24
Enter fullscreen mode Exit fullscreen mode

The same method is used for all objects, but each object prints its own data because every object has its own instance variables.


Comparing Both Approaches

Without Constructor With Constructor
One object stores details of multiple students. One object represents one student.
Many variables like studName1, studName2, studName3 are required. Only one studName and one studAge variable are needed.
Every object contains the same data. Every object stores its own data.
The class must be modified whenever a new student is added. New students can be created simply by creating new objects.
Difficult to maintain. Easy to maintain and extend.
Not a good object-oriented design. Follows object-oriented programming principles.

Top comments (0)