Constructor vs Method in Java

πŸ—οΈ Constructor

A constructor is a special block used to initialize objects when they are created.

βœ… Key Points:

  • Has the same name as the class
  • No return type (not even void)
  • Called automatically when an object is created
  • Can be overloaded (multiple constructors with different parameters)

class Car {
Β  Β  String color;

Β  Β  // Constructor
Β  Β  Car(String c) {
Β  Β  Β  Β  color = c;
Β  Β  }
}

Car myCar = new Car("Red"); // Constructor is called

πŸ”§ Method

A method is a block of code that performs a specific task.

βœ… Key Points:

  • Can have any name
  • Must have a return type (or void)
  • Called explicitly using the object
  • Used for behavior (e.g., actions, calculations)
class Car {
Β  Β  void startEngine() {
Β  Β  Β  Β  System.out.println("Engine started");
Β  Β  }
}
myCar.startEngine(); // Method is called

πŸ“Š Summary Table:

Feature Constructor Method
Purpose Initializes objects Defines object behavior
Name Same as class Any name
Return type No return type Must have return type (or void)
Called by Automatically on object creation Manually using object
Inheritance Not inherited Inherited by child class
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.