Constructors In Java


 

Constructors in Java

 

    Constructor is a block of code which creates the instance of the class. Constructor name should be the class name. It is same as a method but without return type. Constructor will be invoked when we try to create new object to a class with new keyword. It returns object of the class, it implicitly done by the java run-time, we should not add any return type to it. If we try to add return type to a constructor it will be treated as a method but it will show a warning saying “This method has a constructor name”.

Constructors are three types

Ø Default Constructor

Ø No-Args constructor

Ø Parameterized constructor

 

Default Constructor: as we see in the Test.java class we don’t have any constructor then the JVM will implicitly add the Default constructor which having the super() which calling the super class constructor.

 

        

In the above class Test.java we didn’t write any constructor but JVM will add the Default constructor. The JVM will add Default constructor only if the class don’t have any other constructor in the class. The above class will be like as follows with a Default constructor.


No-Args constructor:    A constructor without any arguments is called No-args Constructor. It is used to do some pre-initialization

             

Out Put:


In the above class when we called new Test() then the No-argument constructor is called .

Parameterized constructor:

 Constructor with parameters called Parameterized constructor, which will create the object of the class with parameters specified..


Out Put:


In the above class when the line number 9 executed then the parameterized constructor will be called, and initialize the instance variables and create an object with given parameters.

Note:

 Constructor can be public, protected, default and private, but it cannot be final and static.

Private Constructors are used in singleton design patterns.

 

 



Related Tutorials