"this" keyword plays an important role in Java to reduce the number of lines code and performance. You can observe the following important uses of "this" keyword.
class Employee{
int employeeId;
String employeeName;
Employee(int employeeId,String employeeName){
this.employeeId= employeeId;
this.employeeName= employeeName;
}
void display(){
System.out.println(employeeId+" "+employeeName);
}
public static void main(String args[]){
Employee e1 = new Employee (111,"John");
Employee e2 = new Employee (222,"Abraham");
e1.display();
e2.display();
}
}
class Employee{
int employeeId;
String employeeName;
String company;
Employee(int employeeId,String employeeName){
this.employeeId= employeeId;
this.employeeName= employeeName;
}
Employee(int employeeId,String employeeName, String company){
this(employeeId, employeeName); // No need to initialize employeeId, employeeName
this.company = company;
}
void display(){
System.out.println(employeeId+" "+employeeName);
}
public static void main(String args[]){
Employee e1 = new Employee (111,"John");
Employee e2 = new Employee (222,"Abraham");
e1.display();
e2.display();
}
}
void m(A obj){
System.out.println("method is invoked");
}
class B{
B getB(){
return this;
}
void msg(){
- To refer current class instance variables.
- To invoke current class method.
- To invoke current class constructor.
- To return the current class instance.
Example 1:
class Employee{
int employeeId;
String employeeName;
Employee(int employeeId,String employeeName){
this.employeeId= employeeId;
this.employeeName= employeeName;
}
void display(){
System.out.println(employeeId+" "+employeeName);
}
public static void main(String args[]){
Employee e1 = new Employee (111,"John");
Employee e2 = new Employee (222,"Abraham");
e1.display();
e2.display();
}
}
Example 2:
class Employee{
int employeeId;
String employeeName;
String company;
Employee(int employeeId,String employeeName){
this.employeeId= employeeId;
this.employeeName= employeeName;
}
Employee(int employeeId,String employeeName, String company){
this(employeeId, employeeName); // No need to initialize employeeId, employeeName
this.company = company;
}
void display(){
System.out.println(employeeId+" "+employeeName);
}
public static void main(String args[]){
Employee e1 = new Employee (111,"John");
Employee e2 = new Employee (222,"Abraham");
e1.display();
e2.display();
}
}
- Can be passed as an argument in method
void m(A obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
A a1 = new A();
a1.p();
}
}
m(this);
}
public static void main(String args[]){
A a1 = new A();
a1.p();
}
}
- To return as statement from the method
class B{
B getB(){
return this;
}
void msg(){
System.out.println("Hello World");
}
}
class Test{
public static void main(String args[]){
new B().getB().msg();
}
}
}
class Test{
public static void main(String args[]){
new B().getB().msg();
}
}
Comments
Post a Comment