Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Wednesday, 27 March 2013

This keyword in Java - Example of This keyword in Java

In this particular blog we will see working and functioning of a very basic and commonly used keyword, i.e. this keyword in Java.The 'this' keywords plays an important role in Java programming, in today's discussion we will cover usage of 'this' keyword in details followed by an example program. Lets start our discussion and take a dive into structure and usage of this keyword.

What is 'this' keyword in Java ?

As we all knows Java is a object oriented languge, we have classes as outer wrapper to contain our code, in classes we have number of methods and variables as per our need. In java we creates instances(object) of classes and call methods and variables on these objects. Lets see an example
package com.beingjavaguys.core;

class TestOthers {
    int testVariable;

    public void testMethod(int testVariable) {
        System.out.println("Value of testVariable : " + testVariable);
    }
}

public class TestMain {

    public static void main(String args[]) {
        TestOthers object1 = new TestOthers();
        TestOthers object2 = new TestOthers();

        object1.testVariable = 10;
        object2.testVariable = 20;

        object1.testMethod(50);
        object2.testMethod(50);
    }
}
   
Output :
Value of testVariable : 50
Value of testVariable : 50

In example explained above we have a class 'TestOthers' having a parameterised method 'testMethod(int testVariable)', in main method we created two differenet objects 'object1' and 'object2'. We have set two different values '10' and '20' for 'object1' and 'object2' respectively. When we called 'testMethod(int testVariable)' with these two object we get a value that is passed to constructor i.e. 50. What if we want to print values that are assigned specificly to different objects i.e. 10 and 20. This is where this keyword comes into picture.

The 'this' keyword makes variables and methods to operate on object specific values. It simple words we can say that 'this' keyword makes JVM to refer current object only. In case of variables it refers to the instance variables and not the local variable.
package com.beingjavaguys.core;
class TestOthers {

    int testVariable;

    public void testMethod(int testVariable) {
        System.out.println("Value of testVariable : " + this.testVariable);
    }
}

public class TestMain {

    public static void main(String args[]) {
        TestOthers object1 = new TestOthers();
        TestOthers object2 = new TestOthers();

        object1.testVariable = 10;
        object2.testVariable = 20;

        object1.testMethod(50);
        object2.testMethod(50);
    }
}
   
Output :
Value of testVariable : 10
Value of testVariable : 20

This time we have used a 'this' keyword while refering a variable and it changed the whole picture. We have followed the same functioning as in previous program but the output is purely different. In this case we have passed a value '50' to the constructor but JVM prints the values of instance variable and not the local variable. This is what 'this' keyword does for us in Java.

Except this example, 'this' keyword can be used in many other ways like

1) Using 'this' to get current class Names

The current class name can be get using 'this' keyword as shown in example below.
package com.beingjavaguys.core;

class Apple {

    public void getClassName() {
        System.out.println("Class : " + this.getClass());
    }
}

class Orange {

    public void getClassName() {
        System.out.println("Class : " + this.getClass());
    }
}

public class TestMain {

    public static void main(String args[]) {
        Apple apple = new Apple();
        Orange orange = new Orange();

        apple.getClassName();
        orange.getClassName();
    }
}
   
Output :
Class : class com.beingjavaguys.core.Apple
Class : class com.beingjavaguys.core.Orange

2) Using 'this' keyword to pass current object as parameter.

apple.getClassName(this);
   

3) Using 'this' keyword to return current Object.

This can be used to return current object in a method, as shown below.
package com.beingjavaguys.core;

class Apple {

    public Object getClassObject() {
    return this;
    }
}

public class TestMain {

    public static void main(String args[]) {
        System.out.println(new Apple().getClassObject());    
    }
}
   
Output :
com.beingjavaguys.core.Apple@1f33675

There are some other ways to use 'this' keyword but i every usage the core functionality is same, this is always used to refer the current object whatever the situation is. Today we have seen the usage and functionality of 'this' keyword in java in upcoming blogs we will see what is 'super', 'final' , 'volatile' and 'transient' variables in java.










Thanks for reading !
Being Java Guys Team


6 comments:

  1. Good explanation.When the local variables have the same name as the instance variable,the local variable hides the instance variable.To refer to the instance variable we are using the this keyword.

    ReplyDelete
  2. good explaination.thanx in advance

    ReplyDelete
  3. thank you so much, have looked for so long for an explanation that made sense and finally I found yours!

    ReplyDelete
  4. Understood clearly.Thank u very much

    ReplyDelete
  5. Good one.
    Nice and simple.

    ReplyDelete
  6. Java is one of the popular technologies with improved job opportunity for hopeful professionals. Java Training in Chennai helps you to study this technology in details.

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft