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.
Eg.
public class Employee{
String name;
String designation;
public Employee(String name_){
name=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
this(name_);
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