Monday, May 16, 2011

Calling another constructor in same class using this() in java

Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.


public class Employee{
String name;
String designation;
public Employee(String name_){
public Employee(String name_,String designation_){
//here we are calling constructor with one parameter
//Suppose if we have lots of parameters, this does same some line of code
//and also gives clarity
designation = designation_;

This is also called local chaining of constructors. If we have lots of parameters, this helps us in making code clearer, also saving some effort of typing the line of codes, as we saw above.

No comments:

Post a Comment