Page 238 - Cs_withBlue_J_C11_Flipbook
P. 238

2. Non-Parameterised Constructor: This constructor is used to initialise the instance variables with some initial values.
                 It does not take any parameters.
              3. Parameterised Constructor: This constructor is used to initialise the instance variables with the list of parameters
                 passed to it while creating an object.
                For example,
                Define a class ElectricityBill with the following specifications:

                Data Members                   Purpose
                String n                       stores the name of the customer
                int units                      stores the number of units consumed
                double bill                    stores the amount to be paid
                Member Methods                 Purpose
                ElectricityBill (...)            Parameterised constructor to store the name of the customer and number of
                                               units consumed
                void calculate()               to calculate the bill as per the tariff table given below
                void print()                   to print the details in the format given below
                Tariff table
                Number of units                Rate per unit
                First 100 units                `2.00
                Next 200 units                 `3.00
                Above 300 units                `5.00
                A surcharge of 2.5% is charged if the number of units consumed is above 300 units.

                The output of the preceding program is as follows:
                Name of the customer: ___
                Number of units consumed: _____
                Bill amount:  _____
                Write a main method to create an object of the class and call the above member methods.

                  import java.util.*;
                  class ElectricBill
                  {
                      String n;
                      int units;
                      double bill;
                      ElectricBill(String name,int un)
                      {
                          n=name;
                          units=un;
                      }

                      void calculate()
                      {
                          if (units <= 100)
                              bill = units * 2;
                          else if (units <= 300)
                              bill = 200 + (units - 100) * 3;
                          else
                          {
                              double amt = 200 + 600 + (units - 300) * 5;
                              double surcharge = (amt * 2.5) / 100.0;
                              bill = amt + surcharge;
                          }
                      }


                236236  Touchpad Computer Science-XI
   233   234   235   236   237   238   239   240   241   242   243