Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Constructor Chaining In Java with Examples

Calling a Constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place. This allows you to maintain your initialization from a single location, while providing multiple constructors to the user. If we don’t chain, and two different constructors require a specific parameter, you will have to initialize that parameter twice, and when the initialization changes, you’ll have to change it in every constructor, instead of just the one.


Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword (constructor 3 in below example).
3. Constructor chaining can be achieved in any order.

class Employee
{
public String empName;
public int empSalary;
public String address;

//default constructor of the class
public Employee()
{
//this will call the constructor with String param
this("Skptricks");
}

public Employee(String name)
{
//call the constructor with (String, int) param
this(name, 8765);
}
public Employee(String name, int sal)
{
//call the constructor with (String, int, String) param
this(name, sal, "Delhi");
}
public Employee(String name, int sal, String addr)
{
this.empName=name;
this.empSalary=sal;
this.address=addr;
}

void disp() {
System.out.println("Employee Name: "+empName);
System.out.println("Employee Salary: "+empSalary);
System.out.println("Employee Address: "+address);
}
public static void main(String[] args)
{
Employee obj = new Employee();
obj
.disp();
}
}

Output :
Employee Name: Skptricks
Employee Salary: 8765
Employee Address: Delhi

This is a simple solution, to call one constructor from another in Java. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.



This post first appeared on PHP Update Data In MySQL Database, please read the originial post: here

Share the post

Constructor Chaining In Java with Examples

×

Subscribe to Php Update Data In Mysql Database

Get updates delivered right to your inbox!

Thank you for your subscription

×