×

Java this keyword

This Keyword in Java

This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the term "this" refers to a reference variable that points to the active object in a method or function Object () {[native code]}. This keyword's primary use in Java is to clear up any ambiguity regarding class attributes and parameters with the identical names.

A reference variable in Java is denoted by the term "this." In a Java application, the reference variable "this" refers to the active object. Therefore, you can use the "this" reference to access any member or function of the current object. Given that it refers to the currently selected object, the reference "this" is sometimes known as a "this pointer." When the class attributes and arguments have names, the "this pointer" is helpful. When this happens, the "this pointer" clears out the complication because we may access parameters with the "this" pointer. In a method or function Object () {[native code]}, this keyword refers to the current object.

This keyword is most frequently used to avoid misunderstanding between class attributes and parameters with the same name (because a class attribute is shadowed by a method or function Object () {[native code]} parameter). In the example, the output would be "0" rather than "5" if the keyword were left out.

The word "this" has the following applications in Java:

  • To access the class instance variable, use the reference "this."
  • Even 'this' can be passed as an argument when calling a method.
  • The current class method can also be called automatically by using the 'this' keyword.
  • Use "this" if you want the method to return the current object.
  • 'this' can be used to call the current class's function Object () {[native code]}.
  • The argument "this" can also be passed to the function Object () {[native code]}.

1. this: to refer current class instance variable:

The current class instance variable can be referred to using this keyword. This keyword solves the ambiguity issue if there is any between the instance variables and parameters. Class and method parameters' instance variables may share the same name. The uncertainty that results from this can be resolved by using the "this" pointer.

The Java program that follows shows how instance variables can be accessed using the 'this' keyword.

Example 1:

class thisT
{
     int m;
     int n;
    //constructor of parameter
    this_T(int val1, int val2)
    {
        this.m = m + m;
this.n = n + n;
    }
   void disp()
    {
          System.out.println("Value1m = " + m + " Value2 = " + n);
    }
}
class Main{
       public static void main(String[] s)
       {
            this_T ject = new this_T(5,10);
ject. disp();
       }
}

Output:

Value1m = 10
Value2 n = 20

Example 2:

class Stud{  
int rno;
String name of stu;
float fee;
Stud(int rno,String name of stu,float fee){  
this.rno=rno;
this.name of stu=name of stu;
this.fee=fee;
}  
void disp(){System.out.println(rno+" "+name of stu+" "+fee);}  
}  
class TThis2{  
public static void main (String s []) {
Stud st=new Stud(5h5,"raju",5000f);
Stud st1=new Student(5h4,"deepu",6000f);
st. disp ();
st1.disp();
}}  

Output:

5h5raju 5000.0
5h4deepu 6000.0

It is unnecessary to use this keyword if local variables (also known as formal arguments) and instance variables disagree, as in the following program. You can see that the instance variables and method arguments in the example have the same names. To distinguish between instance variables and method parameters, we utilize the "this" pointer with instance variables.

2. this: to invoke current class method:

Using this keyword, you can call a method of the current class. If this keyword is not used, the compiler will automatically add it when calling the method. I'll give you an example. This pointer may also be supplied as a method argument. When working with events, passing this reference as a method parameter is typically necessary. For instance, if you wanted to start an event on the current object or handle, you would need to use this pointer to start it.

The programming example that follows shows how we gave this pointer to the method.

Example 1:

class Test_mtd
{
    int x;
    int y;
    Test_mtd ()
    {
x = 25;
y = 35;
    }
    void printV1(Test_mtd ob)
    {
             System.out.println("x = " + ob. x + " y = " + ob. y);
    }
    void get()
    {
           printV1(this);
    }
}
class Main{
    public static void main(String [] s)
    {
        Test_mtd obj = new Test_mtd ();
        obj.get();
    }
}

Output:

Value1 x = 25
Value2 y = 35

In this software, the main function creates an object of the class Test method, which is then passed to the get () method. The printV1 () method, which shows the current instance variables, receives the "this" pointer from the get () method.

Example 2:

class T_th {
    void print()
    {
        // calling funsho()
       this.show();
       System.out.println("T_th: print");
    }
    void sh() {
        System.out.println("T_th: sh");
    }
}
class Main{    
    public static void main(String s[]) {
        T_th t = new T_th();
        t.print();
    }
}

Output:

T_th: print
T_th: sh

When the class object in the main function calls the class method print (), it uses this pointer to call the display () method.

Return With ‘this’:

You can quickly return "this" reference if the method's return type is an object of the current class. In other words, a procedure that uses the "this" pointer can return the current object. The implementation for returning an object via the "this" pointer is provided below.

class T_th
{
   int avalue;
   int bvalue;
    //constructor of default
   T_th()
    {
        avalue = 10;
        bvalue = 20;
    }
   T_th get()
    {
        return th;
    }
   void disp()
    {
         System.out.println("avalue = " + avalue + “bvalue = " + bvalue);
    }
}
class Main{
    public static void main(String[] s)
    {
        T_th obje = new T_th();
obje.get ().disp ();
    }
}

Output:

 avalue = 10;
 bvalue = 20;

The program above demonstrates the method get (), which returns this, an object of the class Test this. The get () method then invokes the method display on the current object it returned.

3. this (): to invoke current class constructor:

The current class function Object () {[native code]} can be called using the this () function Object () {[native code]} call. It allows for the function Object () {[native code]} to be reused. In other words, function Object () {[native code]} chaining is accomplished using it. Additionally, you can call the function Object () {[native code]} of the current class using the "this" pointer. Reusing the function Object () {[native code]} is the core concept. Again, if your class has multiple constructors, you can call them all from one another in a process known as function Object () {[native code]} chaining.

Example 1:

class SA {  
SA () {System.out.println("hello raju");}  
SA(int t){  
Th();
System.out.println(t);
}  
}  
class TeTh5{  
public static void main(String s[]){  
SA y=new SA(110);
}}  

Output:

hello a
110

Calling parameterized constructor from default constructor:

Class RA{  
RA(){  
Th(55);
System.out.println("hello raju");
}  
RA(int n){  
System.out.println(n);
}  
}  
class TeTh6{  
public static void main(String s[]){  
RA ta=new RA();
}}  

Output:

55
hello raju

Example 2:

class Th_const
{
     int v11;
     int v12;
    Th_const()
    {   
Th(10, 20);
        System.out.println("Default constructor is ehnanced \n");
    }


    //Here Parameterized constructor is initiated
   Th_const(int v11, int v12)
    {
        this.v11 = v11;
        this.v12 = v12;
        System.out.println("the Parameterized constructor is declared");
    }
}
class Main{
    public static void main(String[] s)
    {
         Th_const obj = new Th_const();
    }
}

Output:

the Parameterized constructor is declared
Default constructor is enhanced

There are two constructors in the class in the program mentioned above. Using the 'this' pointer and the class's default function Object () {[native code]}, we call the other function Object() {[native code]}.

4. this: to pass as an argument in the method:

Additionally, you can give a function Object () {[native code]} the "this" pointer as an argument. This is more useful when you have numerous classes, as in the implementation that follows. The method also accepts this keyword as an input. It is primarily employed while handling events. Here's an illustration:

Example 1:

class SSR1 {  
  void Dee (SSR2 ob) {  
  System.out.println(“invoking the method");
  }  
  void pass (){  
Dee(this);
  }  
  public static void main(String s[]){  
  SSR1 s = new SSR1();
s. pass();
  }  
}  

Output:

Invoking the method

Use of this that is permissible as an argument:

When handling events or when we need to give another class a reference, for example. One object can be used in numerous ways thanks to it.

Example 2:

class SA sec
{
     SB sec bj;


     SA sec (SB sec bj)
    {
        this.bj = bj;
        bj.display();
    }
 }
class SB sec
{
    int a = 20;
    SB sec ()
    {
          SA sec bj = new SA sec(this);
    }
    void display()
    {
          System.out.println("B:a = " + a);
    }
}
class Main{
     public static void main(String[] s) {
        SB sec bj = new SB sec ();
    }
}

Output:

B:a = 20

We have two classes, as demonstrated in the implementation above, and each class's function Object () {[native code]} calls the function Object () {[native code]} of the other class. This is accomplished by using the "this" pointer.

5. this: to pass as argument in the constructor call:

This keyword can also be sent to the function Object () {[native code]}. If we need to use a single object across different classes, it is helpful. Here's an illustration:

Example 1:

class BA {  
  AA4 bj;
  BA (A4 bj){  
    this.bj=bj;
  }  
  void disp(){  
    System.out.println(bj. da) ;//using data member of A4 class  
  }  
}  
class AA4{  
  int da=10;
  AA4(){  
   BA ba=new BA(this);  
ba. display();
  }  
  public static void main (String s []) {
   AA4 aa=new A4();
  }  
}  

Output:

10

We have two classes, as demonstrated in the implementation above, and each class's function Object () {[native code]} calls the function Object () {[native code]} of the other class. This is accomplished by using the "this" pointer.

Example 2:

class ASS
{
	BSSbj;
	// A parameterized function Object () {[native code]} using a BSS object
	// as a parameter
	ASS (BSS obj)
	{
		this.bj = bj;
	//display method of class BSS is called
		bj. disp ();
	}
}
class BSS
{
	int a = 15;
	// Default Constructor that create a object of A
	BSS ()
	{
		ASS bj = new ASS(this);
	}
	
	// method to show value of a
	void disp ()
	{
		System.out.println("Value of a in Class BSS: " + a);
	}
	
	public static void main (String [] s) {
		BAA bj = new BAA ();
	}
}

Output:

Value of a in Class BSS: 5

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

This keyword can be returned from the method as a statement. In this scenario, the method's return type is required to be a class type (non-primitive). Here's an illustration:

This is syntax, which may be used to return a statement:

Returndatatype methodname () {
return this;
}

Example 1:

class AA {  
AA getAA(){  
return this;
}  
void mg () {System.out.println("Hello javatpoint");}  
}  
class T1{  
public static void main(String s[]) {
new AA (). getAA ().mg ();
}  
}  

Output:

Hello javatpoint

Proving this keyword

How about we establish that this keyword corresponds to the current class instance variable? The result of both variables is same since we are printing the reference variable in this application.

class AA5{  
void mg (){  
System.out.println(this);
}  
public static void main(String s[]){  
AA5 bj=new AA5();
System.out.println(bj);//prints the reference ID  
obj.mg ();
}  
}  

Output:

AA22b3ea59
AA22b3ea59

Conclusion

The Java program's current object is indicated with the term "this." It can be used to eliminate misunderstanding brought on by class variables (also known as instance variables) and method arguments having the same names.

This pointer can be used in a variety of ways, such as to access instance variables, supply arguments to methods or constructors, return the object, etc. The Java language's crucial keyword "this" is a practical tool for gaining access to the current object's members and functions.


Related Topics

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.