Page 111 - CTS - CSA TP - Volume 2
P. 111
COMPUTER SOFTWARE APPLICATION - CITS
}
// Method to calculate the perimeter of the rectangle
double calculatePerimeter() {
return 2 * (length + width);
}
}
public class RectangleDemo {
public static void main(String[] args) {
// Create a Rectangle object
Rectangle rectangle = new Rectangle(5.0, 3.0);
// Display the calculated area and perimeter
System.out.println(“Area of the rectangle: “ + rectangle.calculateArea());
System.out.println(“Perimeter of the rectangle: “ + rectangle.calculatePerimeter());
}
}
Output:
Explanation:
• In this program, we define a class Rectangle representing a rectangle with attributes length and width.
• The Rectangle class has methods calculateArea() and calculatePerimeter() to compute the area and perimeter
of the rectangle, respectively.
• We create an instance of the Rectangle class named rectangle with a length of 5.0 units and a width of 3.0
units.
• We call the calculateArea() and calculatePerimeter() methods on the rectangle object to compute and display
its area and perimeter.
• Inside the methods, we access the length and width attributes of the object using the this keyword to perform
the calculations.
This example demonstrates how objects can encapsulate data and behavior within them, allowing us to perform
operations on them effectively. By passing objects to methods, we can invoke their behavior and access their
state to perform various operations and computations, making the code more organized and modular.
96
CITS : IT & ITES - Computer Software Application - Exercise 95