Thursday, 11 April 2024

Returning object using this keyword in Java

public class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    public MyClass doSomething() {
        // Perform some operation, for example, doubling the value
        this.value *= 2;
        // Return the current object
        return this;
    }

    public int getValue() {
        return this.value;
    }

    public static void main(String[] args) {
        // Create an instance of MyClass
        MyClass obj = new MyClass(5);
       
        // Call the doSomething() method and chain it with another method
        System.out.println("Hello"+ obj.doSomething());
        int result = obj.doSomething().getValue();
       
        // Output the result
        System.out.println("Value after operation: " + result); // Output: Value after operation: 10
    }
}

No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...