06 - Polymorphism
06 - Polymorphism
Table of Contents
• Polymorphism
– Definition
– Types
• Override Methods
• Overload Methods
2
ANIMAL
Polymorphism
What is Polimorphism?
Polys Morphe
(many) (shape/forms)
Polymorphos
5
Reference Type and Object Type
6
Keyword – is
• Check if an object is an instance of а specific class
public class Person : Mammal, IAnimal
{}
IAnimal person = new Person();
Mammal personOne = new Person();
Person personTwo = newCheck
Person();
object type of person
if (person is Person)
{
((Person) person).getSalary();
Cast to object
} type and use its
methods
7
Keyword – is
8
Type Pattern
9
Constant Pattern
12
Keyword – As
14
Compile Time Polymorphism
MathOperation
+Add(int, int): int
+Add(double, double, double): double
+Add(decimal, decimal, decimal): decimal
MathOperations mo = new
MathOperations();
Console.WriteLine(mo.Add(2, 3));
Console.WriteLine(mo.Add(2.2, 3.3,
5.5));
Console.WriteLine(mo.Add(2.2m, 3.3m,
4.4m)); 16
Solution: MathOperation
18
Runtime
Polymorphism
• Has two distinct aspects:
• At run time, objects of a derived class may be treated as
objects of a base class in places, such as method
parameters
and collections or arrays
– When this occurs, the object's declared type is no longer
identical to its run-time type
19
Runtime Polymorphism(2)
20
Runtime
Polymorphism
• Also known as Dynamic Polymorphism
public class Rectangle {
public virtual double Area() {
return this.a * this.b;
}
}
public class Square : Rectangle {
public override double Area() {
return this.a * this.a; Method
} overriding
}
21
Runtime Polymorphism (2)
Console.WriteLine(rect.Area());
Console.WriteLine(square.Area());
Method
} overriding
22
Problem: Animals
Animal
string Name
string FavouriteFood
+ExplainSelf():string
Cat Dog
+ ExplainSelf():string + ExplainSelf():string
26
Rules for Overriding Method
27
Rules for Overriding Method
28
Virtual Members
• Virtual members remain virtual indefinitely
• A derived class can stop virtual inheritance by declaring
an override as sealed
• Sealed methods can be replaced by derived classes by
using the new keyword
• The override modifier extends the base class virtual
method
• The new modifier hides an accessible base class method
29
Summary
Polymorphism
… - Definition and Types
…
Override Methods
…
Overload Methods
Abstraction
Classes
Methods
30
Exercises
• Time to practices