Page 299 - CA_Blue( J )_Class10
P. 299

12


                                                                           CONSTRUCTORS
















                           Learning Objectives



                     12.1 Introducing Constructor                    12.2 Different Types of Constructors
                     12.3 Constructor Overloading                    12.4 Difference between Constructor and Method
                     12.5 Similarity between Constructor and Method





                 All objects of any class contain instance variables and data members. These instance variables are required to get
                 initialized so that various operations can be performed by the member methods of the class. To do so, there is a need
                 for using special member method called constructor. Let us study about constructor in detail.


                     12.1 INTRODUCING CONSTRUCTOR
                 A constructor is a type of special member method with same name as of class. However, it is different from a member
                 method as it does not have a return type. A constructor is used to initialize the instance variables of the class. It is also
                 used to initialize the object of the class. The syntax to define a constructor is:

                    class <name of class>
                    {
                        Data members……
                        <name of class>()                     //constructor
                        {
                            job of the constructor like initializing the data members
                        }
                        <member methods>()                                                  Definition
                        {
                            Job of the method                                 A constructor is a method that has the same
                        }                                                     name of the class and used for initialising an
                    }                                                         object.
                 Let us take an example.

                    class book
                    {
                        String name;
                        int no_page;
                        double price;



                                                                                                                       297
                                                                                                         Constructors  297
   294   295   296   297   298   299   300   301   302   303   304