JAVA EXAMPLE: POLYMORPHISM

Polymorphism Concept:
  • Polymorphism means “having many forms” 
  • It is the ability to use the same name to refer to methods that perform different tasks. 
  • Ability of a variable to have more than one type – hold values of different types. 
  • Let us code generically like parameter, it lets us write code that is both general and tailored to a particular situation.


Sample code using polymorphism:

a) Define calcTotCharge() for both classes: Internet & Printing
//calcTotCharge() - printing
public double calcTotCharge()
{
    double totcharge = 0.0;

    if(getColour() == true)
    {
    totcharge = no_of_print*0.70;
    }
    else
    {   
    totcharge = no_of_print*0.30;
    }

    return totcharge;
}

//calcTotCharge() - Internet
public double calcTotCharge()
{
    double totcharge = 0.0;
    int duration=0;
    int st, et;

    st = Integer.parseInt(this.getStartTime());
    et = Integer.parseInt(this.getEndTime());


    duration = et - st;

    if(duration>0 && duration < 120)
    totcharge = 2.50;
    else if(duration >=120);
    totcharge = 2.50  + (((duration - 120)/30)*0.50)
  
    //plus downloaded file charge
    totcharge = totcharge + this.getDownloadedFiles()*1.50;

    return totcharge;
   
}

b)
i) Determine total number of customers who have printed color materials.

int countTotcustColour=0;
for(int i =0; cust.length; i++)
{
    if(cust[i] instanceof Printing)
    {
        Printing temp = (Printing) cust[i];
        if(temp.getColour()==true)
            countTotcustColour++;       
   
    }
   
}
System.out.println("The number of customers use colour:"+ countTotcustColour);

ii) Determine the total charges collected from Internet Service only.


double totChrgInt = 0.0
for(int i =0; cust.length; i++)
{
    if(cust[i] instanceof Internet)
    {
        Internet temp = (Internet) cust[i];
       
        totChrgInt += temp.calcTotCharge();       
   
    }
}
System.out.println("Total charge for Internet service:"+ totChrgInt);


iii) Determine the person's name that downloads the highest number of total downloaded files from Internet in a day.
int highdownload =0;
String name = null;
for(int i =0; cust.length; i++)
{
    if(cust[i] instanceof Internet)
    {
        Internet temp = (Internet) cust[i];
       
        if(temp.getDownloadedFiles() > highdownload)
        {
            highdownload = temp.getDownloadedFiles();
            name = temp.getCustName();
        }
    }
}
System.out.println("The person who download the highest files:"+ name);

2 comments: