Write A Program In Java Demonstrate The Use Of “this” Keyword

0

Write A Program In Java Demonstrate The Use Of “this” Keyword

Write A Program In Java Demonstrate The Use Of “this” Keyword

In this program, we will create a java program to demonstrate the use of “this” keyword.


Before demonstrate the program we will understand the use of "This" keyword.


In java, `this` is a keyword that refers to the current object. It can be used to:

  • Access instance variables and methods of the current object: when a method has local variables with the same name as instance variables, you can use `this` to refer to the instance variables.
  • Invoke a constructor from another constructor in the same class: you can use `this()` to call one constructor from another in the same class.
  • Pass the current object as an argument to a method or constructor: you can use `this` as an argument when calling a method or constructor.
  • Return the current object from a method: you can use `this` as a return value in a method that returns an object of the current class.

Here's a program in java that show the use of "This" keyword:

Program

public class ThisExample {
    int a;
    int b;

    // Parameterized constructor
    ThisExample(int a, int b) {
        this.a = a;
        this.b = b;
    }

    void display() {
        //Displaying value of variables a and b
        System.out.println("a = " + this.a + "  b = " + this.b);
    }

    public static void main(String[] args) {
        ThisExample object = new ThisExample(10, 20);
        object.display();
    }
}

Output
a = 10 b = 20

Explanation

In this example, we have a class thisexample with two instance variables a and b. The class also has a parameterized constructor that takes two arguments. Inside the constructor, we use the this keyword to refer to the current object and assign the values of the arguments to the instance variables.


The display() method uses this to access the instance variables and print their values. In the main() method, we create an object of thisexample and call its display() method.


❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.


Post a Comment

0Comments
Post a Comment (0)