What is the difference between constructor and method in Java

By Saruque Ahamed Mollick

To illustrate the difference between constructor and method in java we firstly, recommend you to read the basic of Constructor and Method in Java.



If you know the basics then you might skip this below portion and directly jump to see the differences between constructor and method in Java.

Remove Duplicate Elements From Unsorted Array And Print Sorted

The concept of constructor in Java

A constructor in Java is just like a method but it is not a method as it does not have any return type.

I heard a lot of people talking about constructor saying that it is a special type of method. But actually, it is not. It constructs the values when the object is created.

Default Constructor in Java: When we create an object with new() keyword, one constructor is called and this is known as default constructor.

Constructor name must be the same as the class name and as I said before it can’t have any return type at all.

A constructor is just like the method but you don’t need to call it. Whenever an object will be created the constructor will be called automatically.

Class Codespeedy {
      Codespeedy() {
       // some code
      }
public static void main(String[] args){
       Codespeedy object_name= new Codespeddy();
    }
}

This is an example of a constructor. Whenever we create an object object_name it means we are calling the constructor at the same time.

Concept Of Class and Object in Java With Examples

 

Method in Java

Method holds some instructions or statements or some block of codes. These codes or statements are executed when the method is called.

Difference between constructor and method in Java

Here are some main key differences between constructor and method in java

  1. Constructors are called at the time of object creation automatically. But methods are not called during the time of object creation automatically.
  2. Constructor name must be same as the class name. Method has no such protocol.
  3. The constructors can’t have any return type. Not even void. But methods can have a return type and also void.
  4. There can be default constructor if no constructor is defined. But there is nothing present known as the default method.

You may also read,

How to read a specific line from a text file in Java

FizzBuzz Problem In Java- A java code to solve FizzBuzz problem

Guess The Number Game Using Java with Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *