This keyword refers to the current object or instance of a class. It allows access to instance variables and methods from within other methods of the same object. This can also be used to invoke the current class constructor from another constructor using this(). Examples show using this to access instance variables when a local variable has the same name, invoking one constructor from another, and passing the current object as an argument to a method.
1 of 6
Download to read offline
More Related Content
Java this keyword ppt with example
1. This Keyword
this keyword refers to the current object in a method or
constructor.
this can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this can be passed as an argument in the method
call.
this can be passed as argument in the constructor
call.
2. Example for this keyword
import java.io.*;
class N
{
int a=30;
void display()
{
int a=40;
System.out.println(a); //output 40
System.out.println(this.a); //output-30
}
public static void main(String args[])
{
N ab=new N();
ab.display();
}
3. this() constructor call can be used to invoke the current class
constructor.
It is used to reuse the constructor.
4. this() :
class A{
A()
{
System.out.println(Welcome");
}
A(int x)
{
this();
System.out.println(x);
}
}
class Ab{
public static void main(String args[])
{
A a=new A(10); //output: Welcome
10
}}
//Calling default
constructor from one
argument constructor
using this keyword
5. Calling parameterized constructor from default
constructor:
class B
{
B()
{
this(5);
System.out.println(Welcome");
}
B(int x)
{
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[])
{
B a=new B();
}}
6. this: to pass as an argument in the
methodclass 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();
}
}