Java Interview QuestionsJava_Language_Features

What Are Java constructors?

Posted On
Posted By admin

A constructor is a special method that is invoked as soon as an object is created using the new operator. In this blog post, I will explaining constructors. Constructors are most commonly used to execute some code that needs to be run as soon as an object of a class is created like setting initial values to the instance variables. Consider the following code snippet:


public class Person {

private String firstName;
private String lastName;

public void setPersonDetails(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
}

Here, there is a Person class. There is a method called setPersonDetails. This method sets values to the firstName and lastName fields. However we need to invoke this method, each time we create a Person object. If we forget to invoke this method, the firstName and lastName fields will not be set . So we need some way for the person details to be automatically set when a Person object is created. Fortunately, Java supports this automatic initialization via constructors. So lets add a constructor to the Person class:


public Person(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}

As you can see, a constructor is very similar to an ordinary method. What sets them apart is that they do not have a return type, not even void unlike other methods defined in a class. Also, the name of the constructor is exactly the same as the name of the class. This constructor is automatically invoked as soon as the new keyword is encountered and the code in the body of the constructor is executed. So as soon as a Person object is created using the new operator this constructor is invoked and it sets the values for the firstName and lastName fields

 

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment