Tag: constructors in java with examples

Constructors in Java

Elements of a class in Java-

Java is a class based language where the entire code is written inside a class.

Any class written in Java consists of the following 5 elements-

  1. Variables
  2. Methods
  3. Constructors
  4. Instance blocks
  5. Static blocks

 

In this post, we will discuss about the constructors of Java in detail.

 

Constructors in Java-

 

Constructor is an element of a class which serves the following two purposes-

  1. Constructors can be used to initialize the instance variables during object creation. (Main purpose)
  2. Constructors can also be used to write the logic of the program which has to be executed automatically on the creation of the objects.

 

When do constructors execute?

 

Constructors are automatically executed on the creation of the objects. Whenever any new object gets created, the constructor corresponding to it is automatically executed.

 

Rules for writing the constructors in Java-

 

There are some rules which we must keep in our minds while working with the constructors. They are as follows-

 

Rule-01:

 

The constructor name and the class name must always be same. So, the while naming the constructor, always make sure that it is same as class name.

 

Rule-02:

 

Constructors can never have any return type (not even void) and that’s why constructors can not return any value explicitly.

However, constructors return instance of the current class implicitly.

 

Note-

If we mention some return type of the constructor by mistake, then we will not get any compile time error or run time error. Compiler considers it as a normal instance method.

 

Example-

 

So, it is perfectly legal to have a method in class having exactly same name as class name but it is not recommended.

 

Rule-03:

 

Only the following listed modifiers can be used for constructors-

  • public
  • private
  • protected
  • default

If we try to use any other modifier, then compiler generates a compile time error saying-

“modifier xxx is not allowed here”

 

Rule-04:

 

The very first line inside every constructor (whether default or parameterized) has to be either this( ) or super( ) with or without arguments where this( ) calls the current class constructor and super( ) calls the super class constructor.

If we don’t mention any of these calling methods, compiler always calls the super class constructor method automatically by writing super( ) as a first statement inside every constructor.

 

Types of Constructors in Java-

 

Constructors are mainly classified into 2 types-

  1. Default constructor
  2. Parameterized constructors

 

 

1. Default Constructor-

 

  • Default constructor is a 0 argument constructor which contains a no argument call to super class constructor.
  • To assign default values to the newly created objects is the main responsibility of default constructor.
  • Compiler writes a default constructor in the code only if the programmer does not write any constructor in the class.
  • The access modifier of default constructor is always same as class modifier. But this rule is applicable only for “public” and “default” modifiers.

 

Syntax-

 

When will compiler add a default constructor?

 

Compiler adds a default constructor to the code only when the programmer writes no constructor in his code from his side.

If programmer writes any constructor in his code, then the compiler does not add any constructor from its side.

Then, it is the responsibility of the programmer to write the default constructor in his code if he requires it.

In that case, it’s no more called a default constructor rather it is called a 0 argument constructor as it is written by the programmer and not added by default by the compiler.

So, It is important to note that-

 

Every default constructor is a 0 argument constructor but every 0 argument constructor is not a default constructor.

 

2. Parameterized Constructors-

 

  • Parameterized constructors are the constructors having specific number of arguments passed to them.
  • The purpose of parameterized constructors is to assign user-wanted specific values to the instance variables of different objects.

 

Difference between default constructor and parameterized constructors-

 

Default Constructor Parameterized Constructors
Default constructor is always a 0 argument constructor. Parameterized constructor have specific number of arguments passed to them.
Default constructor is written by the compiler. Parameterized constructor is written explicitly by the programmer.
Default constructor initializes the instance variables of every object with the same values which are the predefined default values of the variables. Parameterized constructor initializes the instance variables of every object with the different values which are the values passed to the constructor by the programmer while creating the objects.

 

Programmer Code and Compiler Generated Code-

 

It is interesting to know how the code written by the programmer is modified by the compiler after the compilation.

Based on the rules and concepts mentioned above, compiler modifies the programmer’s code.

This has been illustrated with the help of following cases-

 

Case-01:

 

Here, the programmer does not write any constructor inside the class from his side. So, compiler adds the default constructor from its side as shown.

 

Case-02:

 

This case is similar to case-01 except that here the class has been declared with modifier “public” by the programmer. So, compiler adds the modifier “public” to the default constructor that it adds from its side.

(Refer rule-03 above)

 

Case-03:

 

Here, the programmer writes a 0 argument constructor explicitly. So, compiler does not add the default constructor from its side.

However, because inside every constructor, first statement has to be either this( ) or super( ) and because programmer does not write anything out of these from his side so compiler adds the super( ) statement from its side which is a call to the super class constructor.

(Refer rule-04 above)

 

Program illustrating the use of constructors in Java-

class Student
{  
    int roll_no;  
    String stu_name;  
      
    Student(int i , String n)               // Parameterized constructor
    {  
       roll_no = i;                         // Instance Variable
       stu_name = n;                        // Instance Variable
    }  

    void display()
    {
       System.out.println(roll_no+" "+stu_name);
    }  
   
    public static void main(String args[])
    {  
       Student s1 = new Student(1,"Akshay");  
       Student s2 = new Student(2,"Rajat");  
       s1.display();  
       s2.display();  
    }  
}

Output-

1 Akshay
2 Rajat

 

Analysis-

 

In the above program, programmer defines one parameterized constructor with 2 parameters. So, now compiler adds no default constructor to the code and neither the programmer has written any 0 argument constructor.

So, in the above code if we write the following statement in the main method-

Student s3 = new Student( );

Then, a compile time error would be raised by the compiler because there is no 0 argument constructor Student( ) in the code.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.