Page 129 - CTS - CSA TP - Volume 2
P. 129
COMPUTER SOFTWARE APPLICATION - CITS
this.width = width;
}
// Method to calculate the area of the rectangle
double calculateArea() {
return length * width;
}
}
public class RectangleDemo {
public static void main(String[] args) {
// Creating an instance of Rectangle using the parameterized constructor
Rectangle rectangle = new Rectangle(5.0, 3.0);
// Displaying the area of the rectangle
System.out.println(“Area of the rectangle: “ + rectangle.calculateArea());
}
}
Output:
Explanation:
• In this program, we define a class Rectangle with attributes length and width.
• We provide a parameterized constructor for the Rectangle class, which initializes the length and width attributes
with the values passed as parameters.
• In the main method, we create an instance of the Rectangle class using the parameterized constructor, passing
specific values for the length and width.
• We call the calculateArea method of the Rectangle class to calculate and display the area of the rectangle.
TASK 3: Parameterized Constructor in a Student Class
// Student Class using Parameterized Constructor
class Student {
String name;
int age;
114
CITS : IT & ITES - Computer Software Application - Exercise 97