Page 266 - ComputerScience_Class_11
P. 266

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:
                Program 12
                              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.
                              Write a main method to create an object of the class and call the above member methods.

                1       import java.util.*;
                2       class ElectricBill
                3       {

                4           String n;
                5           int units;
                6           double bill;

                7           ElectricBill(String name,int un)
                8           {
                9               n=name;

                10              units=un;
                11          }
                12          void calculate()

                13          {
                14              if (units <= 100)
                15                  bill = units * 2;

                16              else if (units <= 300)
                17                  bill = 200 + (units - 100) * 3;
                18              else





                  264  Touchpad Computer Science (Ver. 3.0)-XI
   261   262   263   264   265   266   267   268   269   270   271