this() constructor call, Real Utilization

Java Programming Language / Class, Object and Methods in java

917

Program:

 class Studentclass{
int rollno;
String name,course;
float age;

Studentclass(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}

Studentclass(int rollno,String name,String course,float age){
this(rollno,name,course);//reusing constructor
this.age=age;
}

void display(){
	System.out.println(rollno+" "+name+" "+course+" "+age);
	}
}

class MainClassOfStudent{
public static void main(String args[]){

	Studentclass obj1=new Studentclass(111,"RAHIM","C");
	Studentclass obj2=new Studentclass(112,"RAM","java",21.5f);
	obj1.display();
	obj2.display();
	}
}

/* The this() constructor call should be used to reuse the constructor
from the constructor. It maintains the chain between the constructors
i.e. it is used for constructor chaining. Let's see the example given
below that displays the actual use of this keyword.
*/

Output:

111 RAHIM C 0.0
112 RAM java 21.5
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.