This-Keyword Simplified in Java

0
57
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

This keyword in Java
This keyword in Java

This keyword in Java:

In general this keyword refers to the current Object.Generally we apply this to a variable which intern refers to the current Object.For instance variables and methods are the property of an object of a class.To access them first we need to create an instance variable that can hold the reference of the object(create an object).
Then using dot(.)  operator, we can access these methods and variables. If we are writing the definition of an instance method(providing definition) and trying to reference to the object that contains the instance method-java provides ‘this’ keyword that we can use in the source code of an instance method to refer to the object that contains the method.


public class MyClass{
private String name;
public MyClass(String name)
{
this.name=name;
}
}
 

Whenever java extends an instance method,it automatically sets the variable.this is to refer the object that contains the method.

What we can do with This keyword?

Well, by this keyword, we can perform the following activities:

  1. refer instance variable of the current class.
  2. invoke or initiate current class constructor.
  3. this – the current object can be passed to a method as an argument
  4. this-the current object can be passed to a constructor as an argument.
  5. This- the current class object can be returned.
  6. Avoid name collision or conflict.
  7. If the  instance variable is hidden by the formal parameter.For assignment statement the value of formal parameter is assigned to instance variable by using this.
  8. We can use this keyword to pass the current object to a method.
  9. We can create a String representation of the current class.

Avoid name collision or conflict

Check the following code:


class myDemo{
private int a; //instance variable a
private int b; //instance variable b
public void myDemo()
{
}
public void myDemo(int a,int b)
//variable a,b send as an argument
{
a=a;
b=b;
}
public void getA()
{
System.out.println("The value of A is"+A)'
}
public static void main(String args[])
{
myDemo md=new myDemo(2,2);
md.getA();
}
}

The output of this code is “The value of A is-0”
The reason we are getting A as zero as compiler does not know which a to pick due to name confusion or name collision.

So rectify this issue , we can take two approaches.

  1. Use of this keyword.
  2. Use different set of variables

Use of this Keyword: Rectify the code used in the assignment.


public void myDemo(int a,int b)
//variable a,b send as an argument
{
this.a=a;
this.b=b;
//this refers to the instance variable of the current object
}
 

The second Approach: Use different variable names instead of the variables used in the Object:


public void myDemo(int c,int d)
//variable a,b send as an argument
{
a=c;
b=d;
}

In this case compiler understand the code and transform the same as :


public void myDemo(int c,int d)
//variable a,b send as an argument
{
this.a=c;
this.b=d;
}

Internally, again they will be converted to


md.a=c;
md.b=d;
//or
md.a=a;
md.b=b; 

We can not use this and super at the same class as both need to be the first line of the constructor code.

lets check one more example:


Class Apple{
void aMethod(int i)
{
....
....
}
}

In main method we will be accessing apple in the following way:


Class MyClass{
public static void main(String args[])
{
//create two instances of Apple as a and b i.e two objects of the same class
Apple a-new Apple();
Apple b=new Apple();
//access the method of the apple
a.aMethod(1);
a.aMethod(1);
}
}

Since the parent class has a method called aMethod(), it should understand which object is calling this method.let us understand how the JVM understands that. JVM silently replaces a.aMethod(1) with Apple.aMethod(1) and b.aMethod(2) with Apple.aMethod(2).

This is the internal mechanism and unexposed to the users.if we need to get the current object handle, we can not access that as the object is passed in a secret way.There is no identifier for it.Java provides a keyword called this for this purpose. This keyword can be used inside a method that produces the handle of the object(current) to the method. This then becomes a regular object handler.
if we are calling a method of our class from within another method of the same class we don’t need to use this keyword.The current this handle is automatically used for the other methods.Compiler does that operation automatically.Thus this keyword is only used for special cases whenwe need to explicitly use this handle to access the current object.


Class MyClass{
void methodA()
{
....
}
void methodB(){
.....
}
void methodC()
{
methodA();// compiler automatically puts this.methodA
methodB();// compiler automatically puts this.methodB
}
}

Use of the this(current object) as a return statement of a method:

In this below code increment() method returns the current object via this keyword. Multiple operations can be done easily using the same concept.


public class MyClass{
    private int i=10;
    public MyClass increment()
    {
        i++;
        return this;
    }
    void println()
    {
        System.out.println("i="+i);
    }
    public static void main(String args[])
    {
        MyClass x=new MyClass();
        x.increment().increment().increment().println();
    }
}

The output of the code:
$javac MyClass.java
$java -Xmx128M -Xms16M MyClass
i=13

How it works:

in the main x.increment() is computed first, it increases the i value by one and return the current object that is x.so the equation becomes
x.increment().increment().increment().println(); i =10
x.increment().increment().println(); i=11
x..increment().println(); i=12
x.println(); i=13
finally println method gets executed.

How to pass current class to a method?


createMyClass(this);//creates a new class from the current class.
System.out.println(this);
//creates a String representation of the current class.
 

How to Work With this Keyword in Java?

This keyword refers to the current object. Now let us understand how to use this keyword.This is used to clear the “confusion of shadow”.

As per Wiki–

this Used to represent an instance of the class in which it appears. this can be used to access class members and as a reference to the current instance. The this keyword is also used to forward a call from one constructor in a class to another constructor in the same class.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here