This Keyword in Java
This Keyword in Java
111 Karan
222 Aryan
If local variables(formal arguments) and instance variables
are different, there is no need to use this keyword like in
the following program:
Program where this keyword is
not required
class Student12{
int id;
String name;
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Output:
Compile Time Error
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as th
is.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output: method is invoked
4) this keyword can be passed as an
argument in the method.
The this keyword can also be passed as an
argument in the method. It is mainly used
in the event handling. Let's see the
example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output: method is invoked
5) The this keyword can be passed as
argument in the constructor call.
We can pass the this keyword in the
constructor also. It is useful if we have to
use one object in multiple classes. Let's see
the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
6) The this keyword can be used to
return current class instance.
We can return the this keyword as an
statement from the method. In such case,
return type of the method must be the
class type (non-primitive). Let's see the
example:
Syntax of this that can be returned
as a statement
return_type method_name(){
return this;
}
Example of this keyword that you
return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
obj.m();
}
}
Output:
A5@22b3ea59
A5@22b3ea59