Page 101 - CTS - CSA TP - Volume 2
P. 101
COMPUTER SOFTWARE APPLICATION - CITS
Explanation
• Rectangle class: It represents a simple geometric rectangle with two properties - length and width. It also
contains methods to calculate the area and perimeter of the rectangle.
• length and width are instance variables that define the state of the rectangle.
• The Rectangle constructor initializes the length and width of the rectangle when an object is created.
• calculateArea() and calculatePerimeter() are methods that calculate the area and perimeter of the rectangle,
respectively.
• RectangleDemo class: It serves as the main class to demonstrate the usage of the Rectangle class.
• In the main method, an object rect1 of the Rectangle class is created using the constructor.
• We access the properties of the rect1 object (length and width) and call its methods (calculateArea() and
calculatePerimeter()).
• The calculated area and perimeter are then printed to the console.
This program illustrates the concept of classes and objects in Java. The Rectangle class encapsulates related
data and behavior, allowing for easier management and manipulation. By creating objects of the Rectangle
class, we can instantiate multiple rectangles with different dimensions and perform operations specific to each
object.
Here are a few more Java programs demonstrating the creation and usage of classes, objects, and methods:
TASK 2: Student Class
class Student {
// Instance variables
String name;
int age;
double grade;
// Constructor
Student(String n, int a, double g) {
name = n;
age = a;
grade = g;
}
// Method to display student information
void displayInfo() {
System.out.println(“Name: “ + name);
System.out.println(“Age: “ + age);
System.out.println(“Grade: “ + grade);
}
}
public class StudentDemo {
public static void main(String[] args) {
// Create an object of Student class
86
CITS : IT & ITES - Computer Software Application - Exercise 94