Difference between constructors and methods in Java

1. Introduction

In Java, both constructors and methods are blocks of code that execute to perform tasks. However, they serve different purposes. A constructor is a block of code that is invoked when an instance of an object is created. Its main role is to initialize the new object. A method, on the other hand, is a block of code that performs a specific task and is called upon by an object's reference.

2. Key Points

1. Constructors initialize new objects and have the same name as the class.

2. Methods perform specific functions and can have any name other than the class name.

3. Constructors are called automatically when a new object is created.

4. Methods must be invoked explicitly using an object reference.

5. Constructors do not have a return type, not even void.

6. Methods usually have a return type. If no data is returned, the return type is void.

3. Differences

Constructor Method
Same name as the class and no return type. Can have any name and usually has a return type.
Called automatically when an instance of a class is created. Must be called or invoked using an object reference.
Used to initialize the state of an object. Used to expose the behavior of an object.
Cannot be inherited, although a subclass can call the superclass constructor. Can be inherited and overridden in a subclass.

4. Example


// Define a class with a constructor and a method
class Car {
    String model;
    int year;

    // Constructor to initialize the Car object
    public Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    // Method to display information about the Car
    public void displayInfo() {
        System.out.println(year + " " + model);
    }
}

public class Main {
    public static void main(String[] args) {
        // Step 1: Create an object using the constructor
        Car car = new Car("Toyota Camry", 2021);

        // Step 2: Call the method on the object
        car.displayInfo();
    }
}

Output:

2021 Toyota Camry

Explanation:

1. The Car class contains one constructor and one method.

2. The constructor Car() is called when a new Car object is created with the new keyword, initializing the model and year.

3. The displayInfo() method is called on the Car object to perform an action, which in this case is printing the car's details.

5. When to use?

- Use a constructor for initializing the state of an object when it is created.

- Use methods to define behaviors and actions that an object can perform.

Comments