Constructors in Java

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)

/*
 * 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 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

/*
 * 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");
	}

	/*
	 * 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 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.

Cheatsheet

  • Constructor is invoked when a new object is created.
  • Constructor’s can also be overloaded but it can not be overridden.
  • Every class has at least one constructor. If user doesn’t provide any JVM will provide a default no arg constructor.
  • Abstract class also has constructor.
  • Constructor must have the same name as class.
  • Constructor can’t have a return type.
  • If a method with the same name as class has return type will be treated as normal member method and not constructor.
  • Constructor can have any access modifier(All).
  • Default constructor is a no arg constructor which calls the no arg constructor of super class. In case super class doesn’t have any no arg constructor then it will throw a run time exception.
  • In case where a class has default constructor, its super class needs to have a no arg constructor.
  • First statement of a constructor can be either this or super but can not be both at the same time.
  • If coder doesn’t write any this  or super call then compiler will add a call to super.
  • Instance member can be accessible only after the super constructor runs.
  • Interfaces do not have constructors.
  • Constructor are not inherited. Hence can not be overridden.
  • Constructor can not be directly invoked. It will be invoked(Implicitly) when a new object is created or a call by other constructor.
Series Navigation<< Java Class & Object Tutorial for beginnersVariables in Java >>
By | 2017-08-14T10:53:30+00:00 April 21st, 2012|Core Java|39 Comments

About the Author:

39 Comments

  1. Siddu February 25, 2014 at 10:45 am - Reply

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

    • Gayathri July 27, 2015 at 6:40 am - Reply

      I think no keyword is required if the constructor name is same as method name…

      • J Singh July 28, 2015 at 10:25 am - Reply

        Which keyword you are talking about Gayathri?

      • chandan March 12, 2016 at 12:34 pm - Reply

        Key words most important if u know keywords you can declaration easily

  2. Siddu February 25, 2014 at 10:46 am - Reply

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

  3. amitabh March 31, 2014 at 5:10 pm - Reply

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

    • praga August 13, 2014 at 2:40 pm - Reply

      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).

      • Ramaiah September 21, 2015 at 4:42 pm - Reply

        we can use constructors in all class but not all in constructors

  4. Sanjay Bhimani August 27, 2014 at 5:44 am - Reply

    @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.

    • sindhu December 31, 2014 at 11:34 am - Reply

      hiiii sir if u dnt mind will u pls explain how to trace java program

      • Saravana Ramki December 30, 2015 at 2:36 am - Reply

        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”);
        }

        • J Singh February 28, 2016 at 11:38 am - Reply

          in example where is return type??

        • Keshav Singh Rajput April 17, 2016 at 11:14 pm - Reply

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

      • Ashish bhardwaj March 30, 2016 at 11:16 am - Reply

        i am also wanted to know”how to trace java programme”

  5. hitesh rakholiya November 12, 2014 at 12:09 pm - Reply

    to create a instance of a class its main purpose of a constructor.

  6. Nishigandha Wagh January 8, 2015 at 5:01 pm - Reply

    Can we define constructor as private?What is purpose of private constructor?

    • Vivekanand Gautam January 10, 2015 at 4:31 pm - Reply

      Yes, We can. Singleton is one of the use of Class having private constructor

  7. Nishigandha Wagh January 26, 2015 at 1:51 pm - Reply

    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?

    • Vivekanand Gautam January 31, 2015 at 1:53 pm - Reply

      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

  8. jaswinder February 22, 2015 at 3:31 pm - Reply

    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

  9. Nandan February 27, 2015 at 6:06 am - Reply

    Sir .i am beginner in java…..this is very useful..thanks alot.. 🙂 🙂

  10. Apurva Mandal September 4, 2015 at 12:05 pm - Reply

    sir, what is singleton class?

  11. daval December 16, 2015 at 4:53 pm - Reply

    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.

  12. muchiri January 12, 2016 at 2:43 pm - Reply

    thanx for assistance

  13. Pranit Desai April 13, 2016 at 9:58 am - Reply

    What is differnce between the implicit and explicit constructor?

    • J Singh April 19, 2016 at 5:29 pm - Reply

      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.

  14. Keshav Singh Rajput April 17, 2016 at 11:12 pm - Reply

    ” 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

    • J Singh April 19, 2016 at 5:27 pm - Reply

      Yes. You understood it correctly.

  15. satnam June 10, 2016 at 7:19 am - Reply

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

    • J Singh June 10, 2016 at 4:37 pm - Reply

      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

  16. satnam June 13, 2016 at 12:09 pm - Reply

    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.

    • J Singh June 13, 2016 at 5:35 pm - Reply

      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

  17. satnam June 14, 2016 at 5:39 am - Reply

    Hi J singh,

    I have poseted the comment but it is not reflecting section ..May I know why.

    • J Singh June 14, 2016 at 5:37 pm - Reply

      It should have been published till now. What is your question?

  18. HARSH September 3, 2016 at 4:59 am - Reply

    sir Plz tell me that which is execute first constructor or init block. and why?

    • J Singh September 3, 2016 at 9:52 am - Reply

      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

  19. Deepak October 16, 2016 at 9:16 am - Reply

    I really appreciate, the quality of tutorials you are providing.

Leave A Comment