Articles

Difference method vs constructor in java

Difference method vs constructor in java

When learning java we should be clear about the difference between java method and java constructor.

 

Constructor vs Method in java differs based on following points:

Naming
Constructor should have same name as the class name in which it is created.
Method may or may not bear the same name as that of the class name. Generally, method is created for specific purpose so its name must reflect its purpose.

Return type:
constructor does not have any return type in java.
method should always be provided with return type in java.

Purpose:
Purpose of having constructor is to initialize state of an object.
Purpose of method is to expose the behaviour of an object.

Default provision:
A default constructor is always provided by java compiler if a programmar doesn't create any constructor.
Method needs to be created by programmar. Its never provided as default.


Example of method in java

We can see a simple example for methods in below code:

public class Calculation {
	int result;
	//Method for addition
	public int add(int num1, int num2){
		result = num1+num2;
		return result;
	}
	//Method for subtraction
	public int substract(int num1, int num2){
		result = num1-num2;
		return result;
	}

	//Method for division
	public float divide(int num1, int num2){
		result = num1/num2;
		return result;
	}
	
}

In the above code:

  • We can see three separate methods created in above code for addition, subtraction and division.
  • The methods accept two parameters of int type and perform the expected calculation.
  • After performing operation they return the result of type int.
  • You can call any of the method using instance of the class from other classes.

Example of constructor in java

Given below is a simple example on constructor:

public class Department {

	private String dept;
	private int deptId;
	private List

In the above code:

  • see the constructor Department has same name as the class name.
  • Constructor accepts 3 parameters. 
  • This constructor will initialize the dept, deptid and subjects for every instances.
  • And most importantly, constructor doesn't have any return type. Only access modifier public is there but no return type like int or String, etc.

 


Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Rohanjit Kumar
Technology geek, loves to write and share knowledge with the world. Having 9+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Jul 05,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!