The following code shows An example of this Keyword in Java.

Problem Statement

Develop an application in Java to create a class called Rectangle and calculate its area using this keyword.

Solution

class Rectangle {
    // Instance variables
    double length;
    double width;

    // Constructor to initialize the length and width
    public Rectangle(double length, double width) {
        this.length = length; // "this" refers to the current instance of the class
        this.width = width;
    }

    // Method to calculate the area
    public double calculateArea() {
        return this.length * this.width; // Using "this" to access instance variables
    }
}

public class RectangleAreaCalculator {
    public static void main(String[] args) {
        // Create an object of the Rectangle class
        Rectangle myRectangle = new Rectangle(5.0, 3.0);

        // Calculate and print the area
        double area = myRectangle.calculateArea();
        System.out.println("The area of the rectangle is: " + area);
    }
}

In this Java program:

  1. At first, we define a class called Rectangle with two instance variables: length and width.
  2. Then, we create a constructor that takes length and width as parameters to initialize the instance variables. Inside the constructor, we use the this keyword to refer to the current instance of the class, which is useful when the parameter names are the same as the instance variable names.
  3. After that, we define a method calculateArea() that calculates the area of the rectangle using the length and width instance variables and returns the result.
  4. In the main method, we create an object myRectangle of the Rectangle class with a length of 5.0 and a width of 3.0.
  5. Finally, we call the calculateArea() method on the myRectangle object to calculate the area and then print the result.

When you run this Java program, it will calculate and display the area of the rectangle using the this keyword to access the instance variables within the class.



Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites