Constructor in Java

Constructors in Java can be seen as a special method in a class. But there is a big difference between Constructor and Method. These differences can be defined in terms of purpose,  syntax, and invocation. A constructor is used in the creation of an object of a class.

Purpose (Constructor Vs Method)

Constructors have only one purpose, to create an instance of a Class. This instantiation includes memory allocation and member initialization (Optional).

By contrast, Methods cannot be used to create an instance of a Class. A method is the combination of statements to perform some task and return some value (Optional).

Syntax (Constructor Vs Method)

/*
 * Here Class name is  ConstructorExample, So constructor name needs to be the same.
 */
public class ConstructorExample {

  /*
   * As below signature has the name as Class name and it doesn't contain any
   * return value so it will be treated as Constructor of the class
   */
  public ConstructorExample() {
    System.out.println("Inside Constructor");
  }

  /*
   * Below method will be invoked only when it is invoked implicitly.
   * Method has return type along with Non Access Modifier
   */
  static void method() {
    System.out.println("This is in method");
  }
}

The syntax of a Constructor is different than a Method as described below.

  • Constructors cannot have Non Access Modifiers while Methods can.
  • Constructors cannot have a return type(Including void) while Methods require it.
  • The Constructor name must be the same as the Class name while Methods are not restricted.
  • As per Java naming convention, Method names should be camelcase while Constructor names should start with a capital letter.

A Method can have the same name as the Class name.

Invocation (Constructor Vs Method)

There is a difference between how constructors and methods are called. Constructors cannot be called explicitly, the constructor will be invoked implicitly when the instance of the class is generated(Using a new Keyword)

Constructor Invocation Example

/*
 * Here Class name is  ConstructorExample, So constructor name needs to be the same.
 */
public class ConstructorExample {

  /*
   * As below signature has the name as Class name and it doesn't contain any
   * return value so it will be treated as Constructor of the class
   */
  public ConstructorExample() {
    System.out.println("Inside Constructor");
  }

  public static void main(String args[]) {
    ConstructorExample cls = new ConstructorExample();
  }
}

// Output will be
// Inside Constructor

Method Invocation Example

/*
 * Here Class name is  ConstructorExample, So constructor name needs to be the same.
 */
public class ConstructorExample {

  /*
   * As below signature has the name as Class name and it doesn't contain any
   * return value so it will be treated as Constructor of the class
   */
  public ConstructorExample() {
    System.out.println("Inside Constructor");
  }

  /*
   * As below signature has the name as Class name and it doesn't contain any
   * return value so it will be treated as Constructor of the class. But
   * as it has parameter it will be called as parameterized constructor.
   */
  public ConstructorExample(String str) {
    System.out.println("Inside Parameterized Constructor");
  }


  /*
   * Below method will be invoked only when it is invoked implicitly.
   */
  void method() {
    System.out.println("This is in method");
  }

  public static void main(String args[]) {
    ConstructorExample cls = new ConstructorExample();
    /*
     * Now method will be called explicitly as below. It will execute the
     * code within method.
     */
    cls.method();
  }
}

  //The output would be Inside Constructor This is in method

A constructor in a class must have the same name as the given class. A Constructor’s syntax does not include a return type, since constructors never return a value. Constructors may also include parameters of various types. A constructor that has one or more parameters is called a parameterized constructor in Java.

When the Constructor is invoked using the new operator, the types must match those that are specified in the Constructor definition.

When no explicit constructors are provided, java provides a default constructor that takes no arguments and performs no special actions or initializations. The only action taken by the implicit default Constructor is to call the superclass constructor using the super() call.

Rules for Constructor

  • A constructor cannot have a return type.
  • A constructor must have the same name as that of the Class.
  • Constructors cannot be marked static
  • A constructor cannot be marked abstract
  •  A Constructor cannot be overridden.
  • A Constructor cannot be final.

Default Constructor

In case the user doesn’t provide a constructor in a class (with or without parameter) JVM will provide a default constructor. This default constructor will be non-parameterized.

If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor(constructor without argument), its implementation must be provided explicitly by the user.

Any attempt to call the default constructor will be a compile-time error if an explicit default constructor is not provided in such a case.

Constructor Overloading

Like methods, constructors can also be overloaded. Since all the constructors in a class have the same name as the class, their signatures are differentiated by their parameter lists.

It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructor invokes the other constructor with the corresponding parameter list within the same class. Java requires that this() call must occur as the first statement in a constructor.

Constructor Chaining

An implicit super() call is included in each constructor which does not include either this() or an explicit super() call as its first statement. The super() statement is used to invoke a constructor of the superclass.

The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor. The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types. A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.

super() or this() construct: If used in the constructor, it must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as this() construct leads to the chaining of constructors in the same class, the super() construct leads to the chaining of subclass constructors to superclass constructors. If a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted implicitly.

If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error.

The subclasses must then explicitly call a Superclass constructor, using the super() construct with the right arguments to match the appropriate Constructor of the Superclass.

Cheatsheet

  • A constructor is invoked when a new object is created.
  • Constructors can also be overloaded but it can not be overridden.
  • Every class has at least one constructor. If a user doesn’t provide any, JVM will provide a default no-arg constructor.
  • Abstract class also has a constructor.
  • A constructor must have the same name as the class.
  • A constructor can’t have a return type.
  • If a method with the same name as a class has a return type, it will be treated as a normal member method and not a constructor.
  • A constructor can have any access modifier(All).
  • A default constructor is a no-arg constructor that calls the no-arg constructor of the superclass. In case the superclass doesn’t have any no-arg constructor then it will throw a runtime exception.
  • In a case where a class has the default constructor, its superclass needs to have a no-arg constructor.
  • The first statement of a constructor can be either this or super but cannot be both at the same time.
  • If the coder doesn’t write any this() or super() call then the compiler will add a call to super(). 
  • super() is used to call the constructor from the superclass.
  • this() is used to call a constructor from the same class.
  • Instance members can be accessed only after the super constructor runs.
  • Interfaces do not have constructors.
  • A constructor is not inherited. Hence cannot be overridden.
  • A constructor cannot be directly invoked. It will be invoked(Implicitly) when a new object is created or called by other constructors.

43 Comments Constructor in Java

    1. JBT

      It can not have because there is no point in having a return value. The only purpose of a constructor is to create an Object and it is called by JVM only. No one else can call it.

      Reply
  1. shrija

    Wonderful points you have mentioned here, your article is very
    petrified me in the learning process and provide
    additional knowledge to me , maybe I can learn
    more from you. Thank you

    Reply
    1. J Singh

      Hi Harsh,

      I have already written an article to show the sequence of block execution. Please have a look at the same.

      Link : javabeginnerstutorial.com/learn-by-example-3/order-of-execution-of-blocks-in-java/

      Regards

      Reply
  2. satnam

    Thanks for your reply .

    Q) Does constructor return any value?
    Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

    I have read it that constructor can return a value but it is mentioned in this article that Constructor cannot have a return value, Please can you explain elaborately.

    Reply
    1. J Singh

      Hi Satnam,

      I don’t know who told you that constructor can have a return type but this is completely wrong. Constructor can not have a return type.

      Regards

      Reply
  3. satnam

    Hi, It is mentioned clearly that Constructor shouldn’t have a access modifier. But How can a contructor be private ??

    Reply
    1. J Singh

      Hi Satnam,

      Please let me know where have i written that Access Modifier can not applied to Constructor? Coz access modifier can be applied to constructor too. And constructor can be private too.

      Regards

      Reply
  4. Keshav Singh Rajput

    ” If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a Superclass constructor, using the super() construct with the right arguments to match the appropriate Constructor of the Superclass”

    Does this mean that if you do not explicitly define a default constructor but only the parametrized constructor, it will not throw a compile time error provided you call the super() with the corresponding arguments in the subclass similar to that of Super class constructor

    Reply
    1. J Singh

      If you define constructor on your own with or without argument, it is called explicit constructor. But if you don’t provide any constructor at all, JVM will provide one without argument constructor. It is called implicit constructor.

      Reply
  5. daval

    I know what is constructor, and constructor chaining. I want to know what are the types e.g what is vertical and horizontal constructor chaining.

    Reply
  6. jaswinder

    hullo sir,i m a beginner sir i want some practical example so that i can do it on my laptop as if i am a student so need to do practice 4 clg exams

    Reply
  7. Nishigandha Wagh

    Sir very nice explaination.But you wrote that “Constructors cannot have Non Access Modifier”
    and you wrote in constructor rules :-“Constructor can be Final.” I am confused.Can you please explain?

    Reply
    1. Vivekanand Gautam

      Hi Nishi,

      That is a typo error. Constructor can’t be Final. Same has been resolved in the Article.
      Hope it help.

      Regards
      Vivekanand Gautam

      Reply
  8. Sanjay Bhimani

    @amithabh

    As per praga said if we not use any constructor then compiler takes no argument constructor and class must follow super class Object using implicit method super(). Now class can use these important methods.

    Another reason is when you create object A a=new A(), Here method A() is going to call So class A must have constructor.

    Very important reason is constructor initializes class. This includes memory allocation to objects. Compiler compiles constructor and static variable in initial phase.

    Reply
      1. Saravana Ramki

        Hi,
        You have mentioned constructor should not have any return type but in your code and the example I can see the return type for the constructor. Please correct me if my understanding is correct or not.

        public ConstructorExample() {
        System.out.println(“Inside Constructor”);
        }

        Reply
    1. praga

      as far as i know, it is optional to use constructor.if user defined constructor is unavailable then compiler creates default constructor just to initialize memory location to members of class(variables).

      Reply
      1. Anmoldeep Singh

        If constructor is declared as method ,then It will not implicitly call by JVM and it will act as normal method.

        Reply

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.