Java Constructor

Java Constructor

Java Constructor, Method and Variable comprises of basic constructs in coding. The importance of Java Constructor is it gives properties to an object at the time of creation itself; else requires many method calls.

Before going into coding, let us know what a Java constructor is. A Java constructor looks like a method but without return type. Moreover, constructor is called implicitly when an object is created.

Let us see one Example on Java Constructor giving properties to an object.

Java ConstructorOutput Screenshot on Java Constructor

In the above class Employee, there are two constructors – one default and one overloaded. A constructor without parameters is known as default constructor and with parameters is known as overloaded constructor. Here, the default constructor just does the job of printing a message. Infact, two access two constructors, two objects should be created. But with one object also other constructor can be accessed. The magic is this(). this() calls the default constructor. The instance variables are assigned in the constructor and used in the main(). If variables are not assigned in constructor, it requires many method definitions and calls.

Following links of this Web site gives indepth study of constructors.

1. Java Constructors: Learn through Questions and Answers
2. Constructor – General Discussion – Overloading
3. What a constructor returns?

Leave a Reply

Your email address will not be published. Required fields are marked *