In this example, we compute the electricity bill of a particular customer. The class ElectricityBil1 contains field customerNo, name and units. It also contains methods setData () show () and billcalculate ().The statement,
ElectricityBill b = new ElectricityBill();
creates a ElectricityBill object in memory and assigns it to the reference variable b. Then the setData () method is invoked that initializes the fields custornerNo,name and units with 001, Dinesh Thakur and 280 values respectively.
The statement,
double billpay = b.billCalculate();
invokes the billCalculate ()method for the object b and stores the result obtained in the billpay variable. Finally, the bill details are displayed.
class Electricitybill
{
private int customerNo;
private String name;
private int units;
void setData(int num,String cname,int nounits )
{
customerNo = num;
name = cname ;
units= nounits;
}
void show()
{
System.out.println("Customer Number : " + customerNo);
System.out.println("Customer Number : " + name);
System.out.println("Units Consumed : " + units);
}
double billcalculate ( )
{
double bill;
if(units<100)
bill = units * 1.20 ;
else if(units <= 300)
bill = 100 * 1.20 + (units - 100) * 2 ;
else
bill = 100 * 1.20 + 200 * 2 + (units - 300) * 3 ;
return bill;
}
};
class ComputeElectricityBill
{
public static void main(String[] args)
{
Electricitybill b = new Electricitybill();
b.setData(001,"Dinesh Thakur", 280);
double billpay = b.billcalculate();
b.show( );
System.out.println("Bill to pay : " + billpay);
}
}