Difference Between Constructors and Methods in Java



Constructors are special methods used to initialize objects, whereas methods are used to execute certain statements. Constructors and methods are both blocks of code inside a class, but they have different purposes. In this article we will learn about the main differences between a constructor and a method.

What is a Constructor in Java?

A constructor is a special method in Java that is automatically called when an object is instantiated. Constructors have the same name as the class and do not have a return type. Its main purpose is to set initial values to the newly created object.

Example

The following example shows the usage of a constructor in Java:

public class JavaTester {
   int num;
   JavaTester(){
      num = 3;
      System.out.println("Constructor invoked. num: " + num);
   }

   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
   }
}

Output

The above program produces the following result :

Constructor invoked. num: 3

What is a Method in Java?

A method, also known as a function, is a block of code that performs a specific task when called. A method should always have a return type. If the method does not return any value, then the return type should be void. The main purpose of a method is to define the behavior of an object, and it also allows us to reuse the code without writing it again.

Example

The following program demonstrates the usage of a method:

public class JavaTester {
   int num = 3;

   public void init(){
      num = 5;
      System.out.println("Method invoked. num: " + num);
   }

   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
      tester.init();
   }
}

Output

The above program produces the following result :

Method invoked. num: 5

Difference Between Constructor and Method

Following are the important differences between Constructors and Methods:

Sr. No. Key Constructors Methods
1 Purpose Constructor is used to create and initialize an Object. Method is used to execute certain statements.
2 Invocation A constructor is invoked implicitly by the System. A method is to be invoked during program code.
3 Invocation A constructor is invoked when new keyword is used to create an object. A method is invoked when it is called.
4 Return Type A constructor can not have any return type. A method can have a return type.
5 Object A constructor initializes an object which is not existent. A method can be invoked only on existing object.
6 Name A constructor must have same name as that of the class. A method name can not be same as class name.
7 Inheritance A constructor cannot be inherited by a subclass. A method is inherited by a subclass.
Updated on: 2025-04-16T15:54:49+05:30

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements