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
Rectanglewith two instance variables:lengthandwidth. - Then, we create a constructor that takes
lengthandwidthas parameters to initialize the instance variables. Inside the constructor, we use thethiskeyword 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 thelengthandwidthinstance variables and returns the result. - In the
mainmethod, we create an objectmyRectangleof theRectangleclass with a length of 5.0 and a width of 3.0. - Finally, we call the
calculateArea()method on themyRectangleobject 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
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
