Local Chaining in Java
-:Local Chaining in Java:-
Local chaining is the process of calling the another constructor from one constructor present in side the same class.This can be achieved by using this() method.
Example 1:
class Student
{
int id;
String name;
//this is zero parameterized constructor
Student()
{
System.out.println("Zero parameterized constructor");
}
//this is parameterized constructor
Student(int id, String name) {
this();
System.out.println("parameterized constructor");
this.id = id;
this.name = name;
}
}
public class Demo {
public static void main(String[] args) {
//creating Student class object with parameterized constructor
Student student=new Student(101,"Rama");
}
}
In this example student class have two constructor one is the parameterized constructor and zero parameterized constructor.when I create the object of the Student class with parameterized constructor this() method get execute and takes the control to the zero parameterized constructor.
Example 2:-
class Student
{
int id;
String name;
String email;
//this is zero parameterized constructor
public Student()
{
System.out.println("Zero parameterized constructor");
}
//this is parameterized constructor
public Student(String name, String email) {
this();
this.name = name;
this.email = email;
System.out.println("parameterized constructor 1");
}
//this is parameterized constructor
public Student(int id, String name, String email) {
this("Raj","Raj@gmail.com");
this.id = id;
this.name = name;
this.email = email;
System.out.println("parameterized constructor 2");
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", email=" + email + "]";
}
}
public class Demo {
public static void main(String[] args) {
//creating Student class object with parameterized constructor
Student student=new Student(101,"Ram","Ram@gmail.com");
System.out.println(student);
}
}
Leave a Comment