DEV Community

Bashar Natheer
Bashar Natheer

Posted on

Learn more about "this" keyword in java oop.

Top comments (1)

Collapse
 
bashar_natheer_8cd5a4f259 profile image
Bashar Natheer • Edited

In Java OOP, the keyword this refers to the current instance of a class. It is useful when differentiating between instance variables and local variables with the same name, passing the current object as an argument, calling another constructor, or enabling method chaining.

Uses of this in Java:

  1. Referring to Instance Variables When a constructor parameter has the same name as an instance variable, this helps distinguish them:
class Person {
    String name;

    Person(String name) {
        this.name = name; // `this.name` refers to the instance variable
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Calling Another Constructor in the Same Class this() can be used to call another constructor within the same class, reducing code duplication:
class Student {
    String name;
    int age;

    Student() {
        this("Unknown", 0); // Calls the other constructor
    }

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Passing this as an Argument The current instance (this) can be passed to another method or constructor:
class Printer {
    void print(Person p) {
        System.out.println("Name: " + p.name);
    }
}

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    void display() {
        Printer printer = new Printer();
        printer.print(this); // Passing the current instance
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Returning the Current Instance (this) Returning this enables method chaining, improving code readability:
class Builder {
    int value;

    Builder setValue(int value) {
        this.value = value;
        return this; // Returning the current instance
    }

    void show() {
        System.out.println("Value: " + value);
    }
}

public class Main {
    public static void main(String[] args) {
        Builder obj = new Builder();
        obj.setValue(10).show(); // Method chaining using `this`
    }
}

Enter fullscreen mode Exit fullscreen mode

When You Cannot Use this

this cannot be used inside static methods because static methods belong to the class, not to a specific instance.

class Example {
    static void staticMethod() {
        // this.name = "Test"; // Error! `this` cannot be used here
    }
}
Enter fullscreen mode Exit fullscreen mode

Summary:

The this keyword in Java is used to refer to the current instance of a class. It helps resolve variable name conflicts, call other constructors, pass the instance as an argument, and enable method chaining. However, it cannot be used inside static methods.