Lecture No 8
Lecture No 8
No.8
Polymorphism &
Overloading
Polymorphism
We can define polymorphism as the ability of a message to be displayed in more than one form.
class Calculator{
public int add(int
a,int b){ return
a+b;
}
public int add(int a,int
b,int c){ return
a+b+c;
}
public int add(int a, int b,int
c,int d){ return
Example (By changing the data types of arguments)
class Calculator{
public int add(int
a,int b){ return
a+b;
}
public int add(int
a,float b){ return
a+b;
}
public string add(int
a,string b){ return
Example (By changing the sequence of arguments)
class Calculator{
public double add(int a,float
b,double c){ return a+b+c;
}
public double add(float a,int
b,double c){ return a+b+c;
}
public double add(double a,float
b,int c){ return a+b+c;
}
}
Task
Create a class called StringHelper with two methods named concatenate. One method takes in two
strings and returns their concatenation. The other method takes in three strings and returns their
concatenation. Create a StringHelper object and call both methods with appropriate parameters.
Task
Create a class called OverloadDemo with three methods named test. One method takes no
parameters, the second method takes in an integer parameter and third method takes in two integer
parameters. Create a forth method takes in double parameter and returns their product. Create an
OverloadDemo object and call above mentioned methods with appropriate parameters
Automatic type conversions apply to
overloading
Constructor Overloading