Constructor overloading

-> Constructor overloading is not complex you just need to create another constructor, obviously same name as of class but different signature but there are certain rules related to Constructor overloading which needs to be remembered while overloading constructor in Java.
-> e.g. One Constructor can only be called from inside of another Constructor and if called it must be first statement of that Constructor. here is an example of correct and incorrect constructor overloading

Example 1:

public loan(){ //Constructor 1 this("" ); //correct } public loan(){//Constructor 2 System.out .println("Calling overloaded Constructor in Java" ); this("" ); //incorrect - throw compilation error. } public loan(String type){ //Constructor 3 this.loanType= type; }

Explanation :

-> If we provide constructor in Class , Compiler will not keep default no argument constructor , so make sure you add a default constructor on your class.
-> In Constructor overloading Number or type of arguments of constructor should be different.
-> Just changing access modifier of Constructor will not result in overloading instead it will throw compilation error as shown in below example:

Example 2:

public loan(String type){//Constructor 1 this.loanType= type; } //compilation error - only access modifier is changed. private loan(String type){//Constructor 2 this.loanType= type; }

Points To be Remeber While Overloading a Constructor :

1. You can call overloaded constructor by using this() keyword in Java.
2. Overloaded constructor must be called from another constructor only.
3. Make sure you add no argument default constructor because once compiler will not add if you have added any constructor in Java.
4. If an overloaded constructor called , it must be first statement of constructor in java.
5. Its best practice to have one primary constructor and let overloaded constructor calls that. this way
6. Though you should remember that once you add a constructor, compiler will not add default no argument constructor.
7. That’s all on Constructor overloading in java. Biggest advantage of Constructor overloading is flexibility which allows you to create object in different way .

   |   

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>