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

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 94 :  Create and  use simple  classes, objects

                                      and methods in JAVA

            Objectives

           At the end of this exercise you shall be able to
           •  know about Create and use simple classes, objects and methods in JAVA
           •  develop Java programs using  classes, objects and Methods.
           Requirements


           Tools/Materials
           •  PC/Laptop  with Windows OS
           •  JDK Software
           •  Text Editor (Visual Studio/Sublime/Notepad)


           Procedure

           Here’s a brief overview of creating and using simple classes, objects, and methods in Java:
           Classes:
           •  In Java, a class is a blueprint for creating objects. It defines the properties and behaviors of objects.
           •  A class is declared using the class keyword followed by the class name.

           •  Inside a class, you define fields (variables) and methods to represent the attributes and behaviors of objects
              of that class.
           Objects:

           •  An object is an instance of a class. It represents a real-world entity and has its own state and behavior.
           •  To create an object in Java, you use the new keyword followed by the constructor of the class.
           •  The constructor initializes the object and allocates memory for it.
           Methods:
           •  Methods are functions defined within a class that perform certain actions or calculations.

           •  Methods encapsulate behavior and can be called to perform specific tasks on objects of the class.
           •  Methods can have parameters (inputs) and return values (outputs).
           Below is a simple Java program that demonstrates the creation and usage of classes, objects, and methods:

           TASK 1: Calculate the area and perimeter of a rectangle using  rectangle class demo
                 // Define a class named Rectangle
              class Rectangle {
                  // Instance variables
                  double length;

                  double width;
                  // Constructor to initialize the rectangle with length and width
                  Rectangle(double l, double w) {









                                                           84
   94   95   96   97   98   99   100   101   102   103   104