DEV Community

Kanishka Shrivastava
Kanishka Shrivastava

Posted on

#java #oop #programming #computerscience

Java Concepts I’m Mastering – Part 4: Constructor vs Method

Continuing my Java fundamentals journey.

Today’s focus: Constructor vs Method — a concept that looks simple but defines how objects behave.

What is a Constructor?

A constructor is a special block of code that:

Has the same name as the class

Is called automatically when an object is created

Initializes object data

class Student {
    String name;

    Student(String name) {   
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

It runs when:

Student s1 = new Student("Kanishka");
Enter fullscreen mode Exit fullscreen mode

What is a Method?

A method:

Has a return type

Is called explicitly

Performs actions

class Student {
    String name;

    void display() {   
        System.out.println(name);
    }
}

Enter fullscreen mode Exit fullscreen mode

It runs only when you call it:

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

Key Differences
Constructor Method
Same name as class Any name
No return type Must have return type
Called automatically Called manually
Initializes object Performs operations

What I Learned

Constructors build the object.

Methods define its behavior.

Clean class design depends on understanding both.

Mastering these small fundamentals makes advanced OOP much easier.

Next in the series: Method Overloading in Java.

Top comments (0)