Have a question?
Message sent Close
View Categories

What is this keyword?

What is this keyword?

📄
filename.js
class Person {

    String name;

    int age;

    // Constructor with parameters

    Person(String name, int age) {

        // 'this.name' refers to the instance variable

        // 'name' refers to the parameter

        this.name = name;

        this.age = age;

    }

    void display() {

        System.out.println("Name: " + this.name);

        System.out.println("Age: " + this.age);

    }

}

public class Main {

    public static void main(String[] args) {

        Person p = new Person("Alice", 30);

        p.display();

    }

}

📄
filename.js
class Calculator {

    void add(int a, int b) {

        int result = a + b;

        System.out.println("Sum: " + result);

    }

    void performAddition() {

        // Calling the add method of the same class

        this.add(5, 10);

    }

}

public class Main {

    public static void main(String[] args) {

        Calculator calc = new Calculator();

        calc.performAddition();

    }

}

📄
filename.js
class Printer {

    void printDetails(Person p) {

        System.out.println("Printing details of: " + p.name);

    }

    void print() {

        // Passing the current object as a parameter

        printDetails(this);

    }

}

class Person {

    String name;

    Person(String name) {

        this.name = name;

    }

}

public class Main {

    public static void main(String[] args) {

        Person p = new Person("Bob");

        Printer printer = new Printer();

        printer.print();

    }

}

📄
filename.js
class Chain {

    int value;

    Chain(int value) {

        this.value = value;

    }

    Chain setValue(int value) {

        this.value = value;

        return this; // Returning the current object

    }

    void display() {

        System.out.println("Value: " + this.value);

    }

}

public class Main {

    public static void main(String[] args) {

        Chain obj = new Chain(10);

        obj.setValue(20).display(); // Chaining method calls

    }

}