Constructors in Java

Constructors are used to initialize the state of an object when it is created. Constructors are invoked while creating objects, usually after the new keyword. A child class may also invoke a super constructor using the super keyword to initialize the parent object.

Constructors are similar in syntax to methods, but without any return type and have the same name as that of the class (case sensitive).

MyClass{

  MyClass(){

  }

}

 

Rules for defining constructors

  1. Constructors have the same name as that of the class.

  2. Constructors are similar to methods in syntax,  but constructors do not have a return type; should not even specify void.

    1. If you specify return type, then the supposed to be constructor will become a method and will not be considered as a constructor.

  3. You can have a method with the same name as a constructor. 

    1. If you specify return type, then it will be considered a method and will not be invoked during initialization; you need to invoke it like just any other method. 

  4. Constructors can also be overloaded just like methods.

    1. You may invoke the correct one based on arguments supplied.

  5. Constructors can be invoked only during object creation or from other constructors using this keyword.

    1. Only one constructor is invoked based on which overloaded version we specify. This constructor can then call other constructors if required, using this keyword (e.g. this() or this(2) etc.).

  6. A default constructor is a constructor that takes no arguments, and mostly does nothing.

  7. A default constructor with no parameters is automatically added by Java for a class if there are no user defined constructors.

    1. Hence, even if we don’t have a constructor for our class, we can instantiate a class using a no-argument constructor ( e.g. new MyClass()).

  8. If we provide at least one constructor, the default constructor is no longer added by Java. 

  9. One constructor can call another constructor using “this” keyword (e.g. this() or this(2)); arguments should match a constructor signature similar to method. You use the method name to specify a method whereas you use the “this” keyword for a constructor. This is called constructor chaining.

  10. Java won’t allow us to create an infinite loop by calling one constructor from another and then the other calling it back either directly or indirectly. Compilation will fail with message “Recursive constructor invocation”. To know more about "this" keyword, refer to keyword-this-in-java.

  11. During inheritance, subclass constructor should call a super class constructor. We use super keyword ti invoke a super class constructor  (e.g. super(), super(1) etc).

  12. First line of a constructor should be a call to super() or this().

    • If you don’t provide any super or this call, constructor will add a call to default super (e.g. super()).

    • If your parent class doesn’t have a visible default constructor, default super call will not work. E.g. parent class has only a private constructor. You either need to add a default constructor in the parent or call any other visible constructors explicitely while creating an object (e.g. with new keyword).

    • This also means that if there are no visible constructors for a class, we cannot inherit that class. For instance, if a class contain only private contructors, you cannot inherit that class or instantiate that class from outside.

      • Refer to the note on singleton for a use case where constructor is made private so that objects can be created only from within the class.

 

Examples

Example: Constructor look-alike method

MyClass{

  void MyClass(){}

}

Here MyClass is a method, not a contructor.

 

Example: Constructor overloading

MyClass{

  MyClass(){

  }

  MyClass(int i){

  }

}

 

Example: Default constructor

To understand the previous rule, create a class without any constructors and instantiate using the default no-parameter constructor.

MyClass{

  public static void main(String[] args)

  {

    MyClass mc = new MyClass();

  }

}

Now add a constructor with parameter and try to execute the same old instantiation:

MyClass{

  MyClass(int i)

  {

  }

  public static void main(String[] args)

  {

    MyClass mc = new MyClass();

  }

}

The code will not compile now as we have provided a constructor with parameter and Java does not provide the default constructor. To compile the code you need to either invoke the new constructor as:

MyClass mc = new MyClass(1);

Or create a no-argument constructor like the default one. To avoid confusion, it is always good have an explicit no-argument constructor.

 

Example: Invalid Invocation

public class MyClass {

  MyClass()

  {

  }

  public static void main(String[] args) {

    MyClass c = new MyClass();

    c.MyClass();

  }

}

Compilation will fail because of the line c.MyClass(). Here MyClass() is a constructor name and we cannot call a constructor as c.MyClass(). Constructors can be invoked only during object creation or from other constructors using this keyword.

 

Example: Not constructor, not method

public class MyClass{

  Myclass()

  {

  }

  public static void main(String[] args) {

    MyClass c = new MyClass();

  }

}

Compilation will fail. Java identifiers are case sensitive and hence MyClass is not same as Myclass. Myclass is not a valid constructor as the name is not same as that of class and not a valid method as it doesn't have a return type. 

Comments

please explain final class , final variable , final object in more detail there lot of confusion  

Was it useful?

Final class cannot be extended (or inherited)

Final primitive variable cannot be assigned another value.

Final reference types (pointing to objects) cannot be assigned another object. However, the object itself can be changed.

For example, Abc abcVar = new Abc();

You cannot do abcVar=new Abc() again or assign anything to varAbc. But you can change any attributes of the Anc object pointed by abcVar as abcVar.setSomething(x);

Just write a simple program and try to do these things (which I said cannot) once, see the errors and let me know if you are still not clear.

You voted 'DOWN'.
Was it useful?

what is the purpose of default constructor?

Was it useful?

Default constructor is a constructor provided by Java if you don't write any constructors.

They allow you to create object of a class using new operator and empty constructor ( MyClass mc = new MyClass()), without creating a constructor of your own. 

Was it useful?

how to call default constructors from parametrized constructor?

Was it useful?

as mentioned before, default constructor is added by Java when there are no other constructors. if you have a parameterised constructor, java won't give you a default constructor. you will have to create a no-arg contructor if you need and then call it as this();

Was it useful?

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)