Page 130 - Computer science 868 Class 12
P. 130

Definition

                    Class is a blueprint or prototype that is required to create objects of the same kind. Thus, a class is said to be a
                    collection of those objects that have the same characteristics and behaviours.



              To create an object, we need to do the following:

                  <classname> <object_name> = new <constructor>;
              For example,

                  sum ob=new sum();
              Here the object ‘ob’ is created which contains all the attributes and methods of the class sum. The “new” operator is
              used to create the object as using it we can create anything dynamically. The method sum() is the constructor which is
              called at the time of creation as it is required to initialise the data member with either default values or with the values
              provided. Let us take the above Student class.

                  import java.util.*;
                  class Student
                  {
                      String name;
                      int cls, roll;
                      double marks_sci, marks_eng, marks_comp;
                      void input()
                      {
                          Scanner sc = new Scanner(System.in);
                          System.out.println("Enter details of student");
                          name = sc.nextLine();
                          cls = sc.nextInt();
                          roll = sc.nextInt();
                          marks_sci = sc.nextDouble();
                          marks_eng = sc.nextDouble();
                          marks_comp = sc.nextDouble();
                      }
                      void cal_result()
                      {
                          double tot_marks = marks_sci+marks_eng+marks_comp;
                          double avg_marks = tot_marks/3.0;
                          System.out.println("Total Marks : "+tot_marks);
                          System.out.println("Average Marks : "+avg_marks);
                      }
                      public static void main()
                      {
                          Student st1 = new Student();
                          Student st2 = new Student();
                          st1.input();
                          st2.input();
                          st1.cal_result();
                          st2.cal_result();
                      }
                  }
              In the above example, the class named Student has created two objects, namely st1 and st2. Each student has got
              different marks and so, their total and average marks are calculated separately.
              We can clearly see that a class can create different objects of the same kind. Thus, a class is a factory of objects.




                128128  Touchpad Computer Science-XII
   125   126   127   128   129   130   131   132   133   134   135