The Best Technical Blog Ever

twitterrss

Constructors in Java

For writing Java programs, we have to create objects at some point. Java constructors are used to instantiate these objects. Every class with objects has a constructor, if we didn't explicitly declare a constructor for a class, then the compiler constructs a default constructor for that class. In this section, we will discuss java constructors, its type and constructors creation with various examples , which will instruct you everything you need to know to get started with Java constructors.


A constructor is a special method which is used to initialize an object. It has same name as the class name in which it resides. They are invoked when an object of class is created. and Constructor does not contain a return type. It is optional to write constructor method in a class. Before we take a look at how to create and use the constructors, first you need to keep in mind that any static initializer block of the program is executed before constructor because they are executed when class is loaded into memory while constructors are executed when you create instance of any object using new() keyword.


Syntax:
Access_modifier Class_Name(parameters) {
       // initialization code
    }

where

  • access_modifier is one of public, protected, or private.
  • Class_Name is the name of the class in which the constructor is defined.


Example :
constructor


This code is the simplest example of constructor. Here, constructor gets called when we create an object of a class. For the above example, when the statement ConstructorExample object = new ConstructorExample(); is executed, it calls the constuctor ConstructorExample() and prints the output "Constructor method is called."


Types of Constructor

There are two types of Constructor.

  1. Default Constructor(no-arg constructor)
  2. Parameterized constructor

Java Default Constructor:

A constructor that have no parameter is known as default constructor.


Example :
constructor


Java parameterized constructor:

Constructor with argument list is known as parameterized constructor. It is used to provide different values to the distinct objects.


Example :
constructor


If a class doesn't define any constructor, then the defines a default constructor and provides the default values to the object like 0, null etc. depending on the type. On the other hand, whenever you declare a constructor, compiler didn't create default constructor.



Constructor Overloading in Java:

Like methods, a constructor can also be overloaded. Constructor overloading is not much different than method overloading. In Constructor overloading, a class can have MORE than one constructor with different signature but only difference is that Constructor doesn't have return type in Java. These overloaded constructors are differentiated by the compiler on the basis of their type of parameters or number of parameters.


When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition. For a class, you cannot write two constructors that have the same type and same number of arguments, because the platform would not be able to differentiate it. So it causes a compile-time error.


Example :
constructor


constructor


The above example shows that the Student constructor is overloaded one being the parameterized constructor with 3 parameters and the other being a parameterized constructor with 4 arguments.



Java Copy Constructor:

In java, there is no copy constructor. But, we can copy the values of one object to another by using one of the following.


  • By assigning the values of one object into another
  • using constructor
  • using clone() method of Object class

Example :
constructor


constructor



Constructor Chaining:

Constructor's are automatically chained by using this() keyword and super(). Constructor chaining is a concept of calling one constructor from another constructor.


We can use this() keyword to call one constructor from another constructor in the same class. This local chaining is possible with this() keyword that invokes the other constructor with the equivalent parameter list within the same class. If a constructor uses this(), it must use it in the first line; otherwise, the compiler will report error message. Below example demonstrates local constructor chaining using this() call.


Example :
constructor


constructor


Constructors use super() keyword to invoke the super class's constructor. Every constructor calls its super class constructor implicitly or explicitly. If a class does not include either the this() function or an explicit super() call as its first statement , then the implicit super() method is invoked by the compiler to call super class's default constructors. If a sub class includes explicit super(), then it replaces the call of implicit super(). The super statement must be the first statement of the constructor; otherwise, the compiler will report error message. The explicit super() invokes the constructor with the equivalent parameter list of the super class. Hence, the explicit super() allows to pass parameter values to the super class constructor that matches its parameter types. This phenomena of calling one constructor from another constructor is known as constructor chaining.


In general, this() and super() calls cannot both occur in the same constructor. If a super class only defines parameterized constructors , then its subclasses will not include an implicit super() call; Otherwise it will be flagged as a compile-time error. Because, implicit super() invokes only default constructor of super class. So, subclasses must then explicitly call a super class constructor, using the super() construct with the right arguments to match the appropriate constructor of the super class. The this() construct always leads to create chaining of constructors in the same class, the super() construct leads to form chaining of subclass constructors to super class constructors. Below is an example of a class demonstrating constructor chaining using explicit super() call.


Example :
constructor


constructor


Below is an example of a class demonstrating constructor chaining without using explicit super() method.


Example :
constructor


constructor

To see Differences between constructor and method in java click here



Key points to remember about constructors

  • Constructor name and class name should be the same.

  • constructor doesn't have any return type. Though you can have return statement inside constructor without returning any value but can return control back to caller. Again, constructors can return current instance of a class. But yet constructor signature cannot have any return type.

  • Constructor can use any access modifier. But scope of the private constructor is only within the class. It prevents a class from extension.

  • If you don't define any constructor within the class, compiler will create default constructor.

  • In java, a class can have as many constructor as it and that is called constructor overloading but signature of two constructor must not be same.

  • Constructors can be overloaded. but constructor overriding is not possible.

  • Constructors can not be inherited.

  • If Super class doesn't have a default constructor then compiler would not define a default one in child class as it does in normal scenario.

  • Constructor chaining : A constructor can invoke another constructor of the same class using this(). In the same way, sub class constructor can also invoke another constructor of parent class by using super().

  • this() and super() should be the first statement in the constructor code.

  • Interfaces do not have constructors.

  • Abstract class can have constructors. This will get invoked when a class implements interface and gets instantiated. (i.e. object creation of concrete class).

  • Constructor in Java cannot be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

  • Constructor can throw Exception in Java using throws clause.
  • Syntax:
    public Class_Name(parameter-list) throws Exception
    {
       // statements
    }


Keypoints to remember in java

1. Java is a high level, robust, secured , platform independent and object oriented programming.... more info

Back to Basics:- Java Syntax

In this session, you are going to refresh some basic set of rules(java syntax), defining how a ... more info

Total Visits
Traffic feed status