Working with Java means you’ll consistently come across various Object Oriented Programming concepts in your development journey. One key concept in OOPs that we’ll address in this article is the constructor. We’ll dive into a discussion about the types and rules of defining constructors, the difference between constructors and methods as well as constructor chaining.
A constructor in Java is special type of method that has the same name as the class it contains and is used to initialize an instance of a class.
Constructors can have any access modifier like public, private and protected and they cannot have a return type.
public class User {
private String name;
private String email;
public User() {}
}
As you can see, we defined a constructor above with the same name as the class User.
Now let’s illustrate how to use the constructor to create an instance of the User class:
public static void main(String[] args) {
User user = new User();
}
We created an object user of type User using the keyword new followed by a call to the constructor.
A humble place to learn Java and Programming better.
Hey, I'm a backend developer and I love to share what I learn with the community.