Page 114 - Cs_withBlue_J_C11_Flipbook
P. 114

Generally, to declare a class, the following components are required:
              1.  Access Specifier
              2.  “Class” keyword
              3.  Class name
              4.  Data members
              5.  Methods
              The data members and methods are encapsulated in curly brackets.

              5.2.1 Creating an Object of a Class
              Instance of a class is also called an object and the process of creating an object of a class is called instantiation.
              The syntax for creating an object:
                  [class name] [space] [object name] = new [space] [constructor];
              For example:
                  book computer = new book();
              A constructor is a function or method that has the same name as the class and is used for initialising an object created
              by the class “book”. You will learn more about constructors later in this book.

              Let’s see an example:

                  class rectangle
                  {
                      int length, breadth, area, perimeter; // Data members
                      void assign() // Method to assign values in length and breadth
                      {
                          length = 5;
                          breadth = 2;
                      }
                      void cal_area() // Method to calculate the area of the rectangle
                      {
                          area = length * breadth;
                      }
                      void cal_perimeter() // Method to calculate the perimeter of the rectangle
                      {
                          perimeter = 2*(length + breadth);
                      }
                      void display()
                      {
                          System.out.println("Area : " + area + " cm");
                          System.out.println("Perimeter : " +perimeter + " cm");
                      }
                      public static void main()
                      {
                          rectangle obj = new rectangle();
                          obj.assign();
                          obj.cal_area();
                          obj.cal_perimeter();
                          obj.display();
                      }
                  }
              What does the above code mean?
              1.  In the above program, an object is being created. The name of the object is “obj”. The line that is used to create the
                 object is “rectangle obj = new rectangle();”.


                112112  Touchpad Computer Science-XI
   109   110   111   112   113   114   115   116   117   118   119