Constructors are special methods used to initialize objects whereas methods are used to execute certain statements. 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. |
Example of Constructor vs Method
JavaTester.java
public class JavaTester {
int num;
JavaTester(){
num = 3;
System.out.println("Constructor invoked. num: " + num);
}
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
Constructor invoked. num: 3 Method invoked. num: 5