JAVA TUTORIAL

Java Intro Java Features Java vs C++ Java Simple Program Java Applet vs Application JVM,JDK or JRE Java Keywords Java Variables Java Literals Java Separators Java Datatypes Java Operators Java Statements Java Array Java String

CONTROL STATEMENTS

Java If-else Java While Loop Java Do-While Loop Java For Loop Java For-each Loop Java Switch Java Break/Continue

JAVA METHODS

Java Method Java Overloading Java Overriding

JAVA CLASSES

Java OOPs Java Classes/Objects Java Inheritance Java Polymorphism Java Encapsulation Java Abstraction Java Modifiers Java Constructors Java Interface Java static keyword Java this keyword

Java this Keyword

In Java, this is a keyword which is used to refer current object of a class. That means we can access any instance variable and method by using this keyword.

Usage of Java this keyword

1. this can be used to refer instance variable of current class

2. this can be used to invoke current class constructor

3. this can be passed as an argument to another method.

4. this can be used to return the current class instance

Example of this Keyword

class Simple {
    int a;

    Simple(int a){
        this.a = a;
    }

    public static void main(String[] args) {
        Simple obj = new Simple(10);
        System.out.println("value of a is = " + obj.a);
    }
}

Output:

value of a is = 10

Using this keyword we call constructor

In java we can call a constructor using this keyword from inside the another function.

Example:

class Simple
{
    Simple()
    {
        // Calling constructor
    this("I'm a constructor of the class Simple");
    }
    
    Simple(String str){
        System.out.println(str);    
    }

    public static void main(String[] args) {
        Simple obj = new Simple();
    }
}

Output:

I'm a constructor of the class Simple

Using this keyword we access method

This is another use of the this keyword that allows to access method. If we want to use implicit object provided by Java then use this keyword. We can also access method using object reference

Example:

class Simple
{
    public void getName()
    {
        System.out.println("Tony Stark");
    }

    public void display()
    {
        this.getName();
    }
    
    public static void main(String[] args) {
        Simple obj = new Simple();
        obj.display();
    }
}

Output:

Tony Stark