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:
- At first, we define a class called
Rectangle
with two instance variables:length
andwidth
. - Then, we create a constructor that takes
length
andwidth
as parameters to initialize the instance variables. Inside the constructor, we use thethis
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. - After that, we define a method
calculateArea()
that calculates the area of the rectangle using thelength
andwidth
instance variables and returns the result. - In the
main
method, we create an objectmyRectangle
of theRectangle
class with a length of 5.0 and a width of 3.0. - Finally, we call the
calculateArea()
method on themyRectangle
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