Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Constructors? 
2.1.
Characteristics of Constructors
3.
What are the Methods?
4.
Constructors vs. Methods
4.1.
Code in Java
4.2.
java
5.
Difference between Constructor and Method
6.
Example of Constructor vs Method
6.1.
java
7.
Frequently Asked Questions
7.1.
Can a method have the same name as the constructor?
7.2.
What is the difference between constructor and main method?
7.3.
What is the difference between constructor and object in Java?
7.4.
What is the difference between constructor and method signature?
7.5.
What is the difference between constructor and method overloading in Java?
8.
Conclusion
Last Updated: Jun 21, 2024
Easy

Difference between Constructor and Method in Java

Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Constructors and methods are two important concepts in object-oriented programming. Both are used to perform different tasks in a class and help in creating and manipulating objects. 

Constructor is a special type of method that is used for proper and valid initialization of the Object of the related class. 

Method, on the other hand, is a function that is defined within a class that is used in manipulating the particular properties inside the Object of that class.

But have you ever wondered what is the difference between Constructor and method?

”difference between constructor and method

In this article, we will compare and contrast the difference between constructor and method, their syntax, purpose, and usage.

What are Constructors? 

Constructors are special methods in object-oriented programming languages like Java, C++, and Python that are automatically called when an object is instantiated. Their primary purpose is to initialize the newly created object, setting initial values for its fields and performing any setup procedures required for the object to function correctly. Constructors have the same name as the class and do not have a return type.

Example in Java:

public class MyClass {
    int value;

    // Constructor
    public MyClass(int initialValue) {
        value = initialValue;
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass(10); // Calls the constructor
        System.out.println(obj.value); // Output: 10
    }
}

 

Characteristics of Constructors

  • The constructor is executed whenever we create new objects of that class.
     
  • Also, it is important to note that a constructor needs to have the exact same name as the class, and it does not have any return type. 
     
  • The Constructor does not return anything. That’s why you do not need to give any return type to the constructor.
     
  • Constructors are very important because they are responsible for the proper initialization of objects. 
     
  • They can also be overloaded with different parameter lists; this allows us to provide different initial states for our object of that class depending on our needs.


For more information, refer to Constructors

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What are the Methods?

A method is what we refer to as a function that is defined within a class, and like any other function, we can pass different parameters to it. 

  • They are integral for manipulating the properties of the class because, when invoked, they can be used to make the required changes.
     
  • Basically, a method is the equivalent of a function in object-oriented programming.
     
  • In methods, we usually operate on the various attributes of the class.

Constructors vs. Methods

Let us take an example to illustrate the difference between Constructor and Method in detail: 

We have a Person class that has two instance variables, name and age, which are declared as private to ensure encapsulation. 

As soon as we create the object of the Person class, the constructor gets invoked. On the other hand, the method needs to be invoked using the object. 

Code in Java

  • java

java

/* Java program to illustrate the difference
  between Constructor and Method
*/
public class Person {
   private String name;
   private int age;


   // constructor
   public Person(String name, int age) {
       this.name = name;
       this.age = age;
   }


   // method
   public void sayHello() {
       System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
   }
  
   // main method
   public static void main(String[] args) {
       Person p = new Person("Ninja", 20);
       p.sayHello();
   }
}


Output

Hello, my name is Ninja and I am 20 years old.


This code demonstrates the difference between constructors and methods, where the constructor is used to initialize the state of an object, and the method is used to perform operations on the object.

Difference between Constructor and Method

Below are some main differences between constructor and method: 

ConstructorMethod
Constructors are used to create and initialise an Object.The method is used to execute certain statements.
A constructor is invoked implicitly by the system.A method is invoked during the program code.
A constructor is invoked when the new keyboard is used to create an object.A method is invoked when it is called.
A constructor cannot have any return type.A method should have a return type.
A constructor must have the same name as the class.A method name can not be the same as a class name.
A constructor cannot be inherited by a subclass.A method is inherited by subclass as well.
A constructor initialises an object which is not existent.A method can be invoked only by an existing object.

Read more about, Difference Between Rank and Dense Rank

Example of Constructor vs Method

Let us discuss an example of a constructor vs method with output:

  • java

java

// This code prints the message "I love coding ninjas"
// and changes the name of the person to "Dhruv"

class Person {
private String name;

public Person() {
this.name = "Dhruv";
System.out.println("Creating a new person named Dhruv");
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return this.name;
}

public void sayHello() {
System.out.println("Hello, my name is " + this.name);
}
}

public class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getName()); // Dhruv
person.setName("Dhruv");
System.out.println(person.getName()); // Dhruv
person.sayHello(); // Hello, my name is Dhruv
}
}


The Person class contains a constructor that initializes the name property to the value "Dhruv". It also has methods to set and get the value of the name property and a method to print a greeting message.

The Main class creates a new Person object and prints the name of the object. After that, it changes the name of the object and prints the name again. Finally, it calls the sayHello() method to print a greeting message.
 

Output:

Dhruv
Dhruv
Hello, my name is Dhruv

Frequently Asked Questions

Can a method have the same name as the constructor?

Yes, a method can have the same name as the constructor, but it should have a different attribute list; this is called method overloading.

What is the difference between constructor and main method?

A constructor initializes an object when it is created, while the main method is the entry point of a Java application, used to run the program.

What is the difference between constructor and object in Java?

A constructor is a special method used to initialize an object, while an object is an instance of a class, representing a specific realization of the class blueprint.

What is the difference between constructor and method signature?

A constructor has no return type and shares the class name, while a method signature includes the method's name and parameter list, optionally with a return type.

What is the difference between constructor and method overloading in Java?

A constructor initializes new objects, while method overloading allows multiple methods with the same name but different parameters within a class, enabling different implementations.

Conclusion

To summarize the discussion, we have discussed the difference between Constructor and method in detail. We have also discussed the types of constructor along with various examples. 

After reading about the key difference between constructor and method, if you feel like going in-depth and knowing more about each of them, Don't worry; Coding Ninjas has you covered.

Refer to Constructors - Coding Ninjas

Constructors and Destructors

Default Constructor in Java - Coding Ninjas

Virtual Constructor and Destructor - Coding Ninjas to learn more about constructors and methods.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
Copy Constructor in Java
Next article
Constructor in Java
Live masterclass