What is difference between constructor and method in Java? Explain with code example

Answer of what is difference between constructor and method in JAVA programming includes differences with code example.

Interview question: Explain difference between constructor and method of a class in java program. explain your points with code by writing a simple class. Also, write code how constructor initializes objects.

Answer:

Constructor Vs Method

Point-1: Constructor must have same name as the class name while this is not the case of methods.
In below example constructor and class both have same name i.e. Insurance. Method does not have same name as class. In example, method is processInsurance().

Code example

class Insurance {
	int year = 0;
	int sum = 0;
	
	//constructor
	public Insurance(int year, int sum){
		this.year = year;
		this.sum = sum;
		System.out.println("Insurance Constructor");
	}
	
	//Method
	public void ProcessInsurance(){
	
		System.out.println("Insurance method");
	}
} 

Point-2: Constructor initializes objects of a class whereas method does not. Methods performs operations on objects that already exist. In other words, to call a method we need an object of the class.

code example:

For above mentioned class Insurance, when we create the object of the class using new the constructor will be called. Note that objects year and sum (class fields) are getting initialized by constructor below, we are initializing year and sum by 25 and 500000 respectively.

to initialize class Insurance object, constructor is used. Method process insurance is called on the object we have created.

public class Program {

	public static void main(String[] args) {

		//constructor will be called on object creation
		Insurance ins =  new Insurance(25, 500000);
		
		//Methods will be called on object created
		ins.ProcessInsurance();

	}

}

Point-3: Constructor is invoked implicitly but method of a class is invoked explicitly.

In above example, we have seen that when we create an object of the class constructor implicitly get called and method is called on created class object explicitly.

Point-4: Constructor does not have return type but a method must have a return type

Here are the snips from the above code of class Insurance. Constructor Insurance does not have return type. While method process insurance has return type “void” even though it is not returning anything.

class Insurance {
	
	//constructor – no return type
	public Insurance(int year, int sum){
		
	}
	
	//Method have void return type
	public void ProcessInsurance(){
	
		System.out.println("Insurance method");
	}
} 

Related Posts