Hey guys in this article, you will understand the difference between Java constructor and Java method
Read More:
- Check the Complete Spring MVC Tutorials
- Check the Complete JSP Tutorials
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
- Check the Spring Boot JdbcTemplate Tutorials
Constructors vs Methods
Following are the difference between Constructors and Methods
Java Constructor | Java Method |
Constructor is used to initialize the state of an object. | Method is used to expose behaviour of an object. |
Constructor must not have return type. | Method must have return type. |
Constructor is invoked implicitly. | Method is invoked explicitly. |
Compiler provides a default constructor if you don’t have any constructor. | Method is not provided by compiler in any case. |
Constructor name must be same as the class name. | Method name may or may not be same as class name. |
Constructors – Example
Following is an example for Constructor
public class Employee {
private int eid;
public Employee() {
}
public Employee(int eid) {
this.eid = eid;
}
}
Methods – Example
Following is an example for Methods
public class Employee {
private int eid;
public int getEmployeeNumber() {
return eid;
}
}
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.