Page 125 - CTS - CSA TP - Volume 2
P. 125

COMPUTER SOFTWARE APPLICATION - CITS





                      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 default constructor for the Rectangle class, which initializes the length and width attributes to
              zero.
           •  In the main method, we create an instance of the Rectangle class using the default constructor.
           •  We call the calculateArea method of the Rectangle class to calculate and display the area of the rectangle.



           TASK 2: Default Constructor with Initialization: Area of a Circle

              //Area of a Circle using Default Constructor with Initialization
               class Circle {
                  double radius;
                  // Default constructor
                  Circle() {

                      radius = 1.0; // Initialize radius to a default value
                  }
                  // Method to calculate the area of the circle
                  double calculateArea() {
                      return Math.PI * radius * radius;

                  }
              }
              public class Circle_Demo {
                  public static void main(String[] args) {

                      // Creating an instance of Circle using the default constructor
                      Circle circle = new Circle();
                      // Displaying the area of the circle
                      System.out.println(“Area of the circle: “ + circle.calculateArea());





                                                           110

                               CITS : IT & ITES - Computer Software Application - Exercise 97
   120   121   122   123   124   125   126   127   128   129   130