Skip to main content

Use of this keyword - Please explain the complex code here

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
rpolic
Offline
Joined: 2013-06-07

class B{
A obj;
B(A obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A class
}
}

class A{
int data=10;
A(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A a=new A();
}
}

Output:10

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
sankarsharma
Offline
Joined: 2014-07-06

Usage of this keyword:

1. this keyword can be used to refer current class instance variable.

2. this() can be used to invoke current class constructor.

3. this keyword can be used to invoke current class method (implicitly)

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this keyword can also be used to return the current class instance.

read more in detail:-
http://www.javatpoint.com/this-keyword