Constructors in Java

This entry is part 4 of 34 in the series Core Java Course

Constructors in Java can be seen as Methods in a Class. But there is a big difference between Constructors and Methods. These differences are defined in terms of purpose,  syntax and invocation.

Purpose of Constructor in Java (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.

Syntax of Constructor(Vs 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 capital letter.
Note*: A Method can have the same name as the Class name.

Invocation of 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 new Keyword)

Constructor Invocation Example

 

Method Invocation Example

A Constructor in a Class has 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. When the Constructor is invoked using the new operator, the types must match those that are specified in the Constructor definition. Java provides a default Constructor which takes no arguments and performs no special actions or initializations, when no explicit Constructors are provided.

The only action taken by the implicit default Constructor is to call the Superclass Constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an Object.

Constructor in Java Rules

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

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, its implementation must be provided. 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 the Constructors in a Class, all 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 any this() call must occur as the first statement in a constructor.

Constructor Chaining:

Every Constructor calls its Superclass constructor. An implied super() is therefore included in each constructor which does not include either this() or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.

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 constructor, 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 the this() construct leads to chaining of constructors in the same class, the super() construct leads to 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.

 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.

Series Navigation<< Java Class & Object Tutorial for beginnersVariables in Java >>

39 Comments Constructors in Java

  1. Siddu

    Its good explanation, Is there any technical reason why constructor should be the same name as class name?

    Reply
  2. Siddu

    Whats the use of co-variant features in java?
    Whats the use of assert statement over exception classes?

    Reply
  3. amitabh

    why used constructor ? and what is advantage?
    not used constructor in java then what happened ……..

    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
  4. 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. Keshav Singh Rajput

          public is not a return type, its an access modifier.
          Constructor cannot have a return type.

          Reply
  5. 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
  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. 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
    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
  8. 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
  9. 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
  10. 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
  11. satnam

    Can you please give me your mail Id or can you please mail me at [email protected].

    My ques is not reflecting in Comment section. So I am not sure whether is posted or not.

    Regards,
    Satnam

    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

Leave A Comment

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