Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

This Keyword In Java

this keyword in java can be used inside the method or constructor of Class. It(this) contains the reference of the current Object whose method or constructor is being invoked. The this keyword can be used to refer the member of the current object from within an instance method or a constructor.
this-keyword-in-java


Use Case of this Keyword

 Case 1 :- this keyword is used to distinguish between local variable and instance variable inside constructor and method.

public class Student  {

   private String name;

   public void setName(String name)  {
        // "this" keywords makes it clear that you are assigning 
        // the value of the argument "name" to the 
        // instance variable "name".
        this.name = name;
    }
}

 Case 2 :- 'this' keyword can be used as an argument passed to another object.

public class Company {
    private String name="Gps Infosolution";
    private Employee emp = new Employee();

    public String useEmpMethod() {
        return   emp.empMethod(this);
    }
    public String getName() {
        return this.name;
    }
}

public class Employee  {

    public String empMethod(Company cmpny)  {
        String CompanyName = cmpny.getName();
    }
}

 Case 3 :- Using this keyword to call another constructors(chaining).
When you have multiple constructors in a single class(constructor overloding), you can use this(arg0, arg1, ...) to call another constructor of same class.

constructor-chaining-in-java