Difference between Constructor and Method in Java

Java is an Object-Oriented Programming language. Therefore, the data and the member functions in Java are present in the classes. The classes in Java contain both constructors and methods as well. Let’s see in detail about methods and constructors and their differences.

Constructor

The purpose of constructors is to initialize the objects, which are the instances of the classes. Similar to the methods, the constructors also hold statement blocks that get executed during the run time of the program. Constructors are compulsory in Java. Even though you don’t make one, the Java compiler adds a default constructor in your program. Whenever you create an object with the new() keyword, one constructor always gets invoked.

Example:

Output:

Constructor called
null
0

Method

Methods in Java are a collection of statements that get executed during the run time. The statements inside the methods block perform some particular task and then return an outcome to the caller. It is not compulsory for the method to always return something. The purpose of member functions is the reusability of the code. In Java, a function is always a part of a class, unlike in other languages like C++ and C.

Example:

Output:

Sum of two integers is: 5

Now let’s see the points that make the methods and constructors different from each other:

Constructor Method
The purpose of the constructor is to initialize the objects that are created. The purpose of the method is the reusability of a code.
A constructor can be invoked implicitly by the system. Methods are always invoked by the programmers.
It gets invoked when an object is created using the new() keyword. It gets invoked when a method is called inside the program.
A constructor name is always similar to that of the class name. A method name could be anything.
A constructor cannot have a return type and value. A method should have a return type and value.
Subclasses cannot inherit the constructors of the main class. Methods can be inherited by the subclasses.

Comment down below if you have any queries related to the above article.

Leave a Reply

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