Write a program in Java to demonstrate use of this keyword. Check whether this can access the private members of the class or not.

Here's an example Java program to demonstrates the use of the this keyword and shows that it can access the private members of the class:

Create a Example.java file and write this code in it.

public class Example {
    private int number;

    public Example(int number) {
        this.number = number;
    }

    public void printNumber() {
        System.out.println("The number is: " + this.number);
    }

    public static void main(String[] args) {
        Example example = new Example(42);
        example.printNumber();
    }
}

In this example, we have a class called Example with a private member variable number. The constructor of the class takes an integer parameter and assigns it to the number variable using the this keyword to refer to the instance variable.


Comments