0% found this document useful (0 votes)
6 views31 pages

06 - Polymorphism

The document provides an overview of polymorphism in object-oriented programming, detailing its definition, types (compile-time and runtime), and the concepts of method overriding and overloading. It explains how polymorphism allows objects to take on multiple forms and includes examples of using keywords like 'is' and 'as' for type checking and casting. Additionally, it outlines rules for method overloading and overriding, emphasizing the importance of signatures and virtual methods.

Uploaded by

KL M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views31 pages

06 - Polymorphism

The document provides an overview of polymorphism in object-oriented programming, detailing its definition, types (compile-time and runtime), and the concepts of method overriding and overloading. It explains how polymorphism allows objects to take on multiple forms and includes examples of using keywords like 'is' and 'as' for type checking and casting. Additionally, it outlines rules for method overloading and overriding, emphasizing the importance of signatures and virtual methods.

Uploaded by

KL M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Lecture 06: Polymorphism

Table of Contents

• Polymorphism
– Definition
– Types
• Override Methods
• Overload Methods

2
ANIMAL

Polymorphism
What is Polimorphism?

• From the Greek

Polys Morphe
(many) (shape/forms)

Polymorphos

• This is something similar to a word having several


different meanings depending on the context
• Polymorphism is often referred to as the third pillar of
object-oriented programming, after encapsulation and
inheritance
4
Polymorphism in OOP

• Ability of an object to take on many forms


public interface IAnimal {}
public abstract class Mammal {}
public class Person : Mammal, IAnimal {}

Person IS-A Person Person IS-AN Animal

Person IS-A Mammal Person IS-AN Object

5
Reference Type and Object Type

• Variables are saved in a reference type


• You can use only reference methods
• If you need an object method you need to cast it or override it

public class Person : Mammal, IAnimal {}


IAnimal person = new Person();
Mammal personOne = new Person();
Person personTwo = new Person();

Reference Type 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

• IS statement supports pattern matching:


– Type pattern - tests whether an expression can be converted
to a specified type and casts it to a variable of that type
– Constant pattern - tests whether an expression evaluates
to a specified constant value
– var pattern - match that always succeeds and binds the value
of an expression to a new local variable

8
Type Pattern

public class Person : Mammal, IAnimal


{}
Mammal personOne = new Person();
Person personTwo = new Person();
Checks if object is of type
if (personTwo is Person person) person and casts it
{
person.GetSalary();
Uses its
} methods

9
Constant Pattern

• When performing pattern matching with the constant


pattern,
is tests whether an expression equals a specified
constant int i = 0;

• Checking for null can const max = 10;


while(true)
be performed using {
the constant pattern Console.WriteLine($”i is {i}”);
i++;
if(i is max) break;
}
10
Var Pattern

• A pattern match with the var pattern always succeeds


If (expr is var varname)
{
// Do something with varname
}

• The value of expr is always assigned to a local variable named


varname
• varname is a static variable of the same type as expr
• Note that if expr is null, the is expression still is true and assigns
null
to varname
11
Keyword – is

Anytime you find yourself writing code of


the form "if the object is of type T1,
then do
something, but if it's of type T2, then do
something else", slap
Fromyourself.
Effective C++, by Scott Meyers

12
Keyword – As

• You can use the as operator to perform certain types of


conversions between compatible reference types
public class Person : Mammal, Animal
{}
Animal person = new Person();
Mammal personOne = new Person(); Convert Mammal to Person
Person personTwo;
personTwo = personOne asCheck if conversion is
Person;
if (personTwo != null) successful
{
// Do something specific for Person
}
13
Types of
Polymorphism
• Compile time
• Runtime public static void Main()
public class Shape {} {
public class Circle : Shape int Sum(int a, int b, int
{} c)
public static void Main() double Sum(Double a, Double
b)
{
}
Shape shape = new
Circle()
}

14
Compile Time Polymorphism

• Also known as Static Polymorphism


public static void Main()
{
static int MyMethod(int a, int b) {}
static double MyMethod(double a, double b) { … }
}
Method
overloading
• Argument lists could differ in:
– Number of parameters
– Data type of parameters
– Order of parameters
15
Problem: MathOperation

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

public int Add(int a, int b)


{
return a + b;
}
public double Add(double a, double b, double c)
{
return a + b + c;
}
public decimal Add(decimal a, decimal b, deci-
mal c)
{
return a + b + c;
}
17
Rules for Overloading a Method

• Signature should be different


– Number of arguments
– Type of arguments
– Order of arguments
• Return type is not a part of its signature
• Overloading can take place in the same class or
in its sub-classes
• Constructors can be overloaded

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)

• Base classes may define and implement virtual methods


– Derived classes can override
– They provide their own definition and implementation
• At run-time, the CLR looks up the run-time type of the
object
and invokes that override of the virtual method

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)

• Usage of override method

public static void Main()


{
Rectangle rect = new Rectangle(3.0,
4.0);
Rectangle square = new Square(4.0);

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

Check your solution here: https://judge.softuni.bg/Contests/1503/Polymorphism-Lab 23


Solution: Animals

public abstract class Animal {


// Create Constructor
public string Name { get; private set; }
public string FavouriteFood { get; private
set; }
public virtual string ExplainSelf() {
return string.Format(
"I am {0} and my favourite food is {1}",
this.Name,
this.FavouriteFood);
}
}
24
Solution: Animals
(2)
public class Dog : Animal
{
public Dog(string name, string favourite-
Food)
: base(name, favouriteFood) { }
public override string ExplainSelf()
{
return base.ExplainSelf() +
Environment.NewLine +
"BARK";
}
}
25
Solution: Animals
(3)
public class Cat : Animal
{
public Cat(string name, string favouriteFood)
: base(name, favouriteFood) { }
public override string ExplainSelf()
{
return base.ExplainSelf() +
Environment.NewLine +
"MEOW";
}
}

26
Rules for Overriding Method

• Overriding must take place in any sub-classes


• The overriding method and the base must have the same
return type and the same signature
• Base method must have the virtual keyword
• Overriding method must have the abstract or
override keyword
• Private and static methods cannot be overridden

27
Rules for Overriding Method

• Virtual members use base keyword to call the base


class
• Occurring base class behavior enables the derived class
concentrate on implementing specific behavior
• If the base implementation is not called, the derived class
has to make their behavior compatible with the behavior
of the base class

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

You might also like