digitization, transformation, binary

This-Keyword Simplified in Java

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.

READ  Class SequenceInputStream in Java

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

READ  Collection Framework Simplified in Java

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.

I will try to implement the Wiki’s argument about this keyword.

public class Class1 {
int x,y;
public Class1(int x,int y) {
x=x;
this.y=y;
}
}

Now if you are using an upgraded editor like jDeveloper it will automatically point out a warning on line where it is defined-x=x;

Why ??
Well here java got confused ??
the variable x is a new variable or the global variable?? And assuming it is a local variable java will print 0 as an output.But for second line this.y=y will surely make java understand that it is referring to the global variable.So it will print the correct value.

So importance of this keyword to avoid variable name conflict.

The this keyword helps in removing the ambiguity of references and allows to refer to the current instance within the running program.
— key word this is used with variables as “this.variable” and specifies the number of member variable of this instance of that class

this keyword can also be used to pass the current object of the class.Always remember this keyword can not be used in the static context . Java will throw an compilation error.

READ  How To Handle Keyboard and Mouse Operation In Selenium Via Action class?

Now if there is no name conflict a scenario I have created….

public class Class1 {
int x,y;
public Class1(int a,int b) {
x=a;
this.y=b;
}
public static void main(String[] args) {
Class1 class1 = new Class1(30,40);
System.out.println(class1.x);
System.out.println(class1.y);
}
}

This will not throw any wrong value.But it will create problem when you call it second time.

public class Class1 {
int x,y;
public Class1(int a,int b) {
x=a;
this.y=b;
}

public static void main(String[] args) {
Class1 class1 = new Class1(30,40);
System.out.println(class1.x);
System.out.println(class1.y);
Class1 class2 = new Class1(50,60);
System.out.println(class1.x);
System.out.println(class1.y);
}
}

The instance variables are set with the first set of values and not able to update with second set of values. so the above written code is only applicable if that is a singleton class.

Else the class has to be synchronized.otherwise if two class trying to acess the same method that time it will be a mess.

What does the this keyword do??
when called during runtime this is replaced by the calling object.So..

this.x=x becomes class1.x=x;
this.y=y becomes class1.y=y;

again if a call comes from Class2

this.x becomes Class2.x=x;
this.y becomes Class2.y=y;

This is done by object handler automatically.
The forth implementation could be- the chaining of constructor..Wow!! what is that?

class Class2
{
public Class2()
{
this(1);
System.out.println("First Constructor");
}
public Class2(int a)
{
this(1,2);
System.out.println("Second Constructor");
}

/**
* @param a
* @param B
*/
public Class2( int a, int b)
{
this("Testing chain");
System.out.println("Third Constructor");
}
public Class2(String s)
{
System.out.println("Fourth Constructor");
}
public static void main(String args[])
{
Class2 first = new Class2();
}
}

What will be the output

Fourth Constructor
Third Constructor
Second Constructor
First Constructor
How??
When we call the default constructor

Class2 first = new Class2();

control goes to the default method..

public Class2()
{
this(10);
System.out.println("First Constructor");
}

Here the first line says this(10)..this nothing but to call the Class2(int a)
so the control goes to

public Class2(int a)
{
this(1,2);
System.out.println("Second Constructor");
}

And so on..
After that it will come back to calling method and perform remaining activities.

So as per our discussion,the specialized use of the this keywords arises when a class has multiple constructors, it can be used from a constructor to invoke one of the other constructors of the same class.

this() call refers to whatever constructor of the class takes the specified type of arguments.

There is a very important restriction on this keyword. It may only appear as the first statement in a constructor. There could be other initialization the constructor needs to do. The reason for this restriction involves the automatic invocation of the super class constructor method.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *