SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
Inheritance & Polymorphism
Eng Teong Cheah
Microsoft MVP Windows Development
Inheritance
Inheritance
C# is an object oriented programming language so it supports one key feature of OOPS;
Inheritance.
In general, Inheritance can be explained as acquiring the properties of the parent.
For this, we will use the most common example of the car class.
You can see Car is an Object who has basic feature like name, height, no of wheels. It has two
specialized version one is sedan and other is hatchback. Both sedan and hatch back has all the
basic feature of car and some specialized property of their own. This feature is known as
inheritance.
Inheritance
When a child class has all the features
of base class plus its own specialized
properties. Then this phenomenon is
known as inheritance.
Inheritance
Types of inheritance supported by C# are follows:
- Single inheritance
Single base class and single derived class.
- Multilevel inheritance
B derive from A and C derive from B.
- Hierarchical inheritance
B and C both derived from A.
- Multiple inheritance using Interfaces
Class D derived from Interface A, Interface B and Class C.
Inheritance
Preventing a Class from Being Inherited C#
We can prevent the class from Being Inherited by Other Class by putting Sealed Keyword in class.
See Example Below:-
sealed class stringHandler
{
public string inputString { get; set; }
public string OutputString { get; set; }
public stringHandler(string inputstring)
{
this.inputString = inputString;
}
public String FormatString()
{
// Some Code here
}
}
Inheritance
Constructor initialization C# Inheritance
See the car example on top of this page, if we create an object of HatchBack class . The
constructor initialization series is given below –
HatchBack hb = new HatchBack("hatchback",4,125,40,true);
1. First Car constructor is initialized
public Car(string name, int wheelcount, float length, float
breadth)
{
this.Name = name;
this.WheelCount = wheelcount;
this.length = length;
this.breadth = breadth;
}
Inheritance
2. Second Hatchback Constructor will be initialized
public HatchBack(string name, int wheelcount, float length,
float breadth, bool isconvertible) : base(name, wheelcount,
length, breadth)
{
this.IsConvertible = isconvertible;
}
So, from these examples we can say that constructor initialization in inheritance will always follow
from base to derived downwards.
Inheritance
Calling Base class’s Constructor in Inherited C#
Classes :
Base class constructor is called in derived class using
base Keyword. See Car example on top of the
page Calling a Base class’s Hidden members in
inherited class C# :
Base class hidden member function can be called by
using base.functionname syntax.
See Example below -
Inheritance
Type Casting in Inheritance C#
Parent class reference can hold child class reference but
opposite is not true. Casting an object to a parent class
is called upcasting. Casting an object to child class is
called downcasting.
See Example below -
We have Draw() method both in base class and derived
class. But the see which one is called when.
If the Shape class’s Draw() Method is declared as virtual
and overridden in Oval class’s Draw() method then result
would be different. Result would be.
Output when Draw() method will be declared as Virtual
and overridden in derived class :
Shape Drawn
Oval Drawn
Oval Drawn
Polymorphism
Polymorphism
Polymorphism is one of the key features of OOPS. Polymorphism can be broken as below.
Polymorphism =Poly + morphism =Multiple + forms.
Polymorphism is simply calling derived class methods from base class reference during runtime. It
is the behavioural change of methods depending upon the instance called at runtime.
Polymorphism
Before we understand it in polymorphism in C# language, let’s understand it with a simple fantasy
example.
A mermaid, yes a mermaid. Viola……But how a mermaid is related to Polymorphism see image
below.
Mermaid shows a polymorphic
behavior according to
environment.
Mermaid behaves like human
while on earth and as a fish
while in water.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this
text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the
easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is
inherited in the two subclasses
Inherited Methods
The method Foo() can be overridden in classes B and C:
Inherited Methods
There are two problems with this code.
- The output is not really what we, say from Java, expected. The method Foo() is a non-virtual
method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An
example using virtual methods and polymorphism will be given in the next section.
- Although the code compiles and runs, the compiler produces a warning:
...polymorphism.cs(11,15): warning CS0108: The keyword new is required on
'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly
declared to override the virtual base class method with the override keyword.
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports
method overriding, but also method hiding. Simply put, if a method is not overriding the derived
method, it is hiding it. A hiding method has to be declared using the new keyword. The correct
class definition in the second listing is thus:
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In
order to declare such a method, both keywords virtual and new have to be used in the method
declaration:
Combining Method Overriding and Hiding
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
Demo
Resources
• MSDN
• Techoschool

Mais conteúdo relacionado

Mais procurados

8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
Tuan Ngo
 

Mais procurados (20)

Inheritance polymorphism-in-java
Inheritance polymorphism-in-javaInheritance polymorphism-in-java
Inheritance polymorphism-in-java
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java interface
Java interfaceJava interface
Java interface
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Abstract classes and interfaces
Abstract classes and interfacesAbstract classes and interfaces
Abstract classes and interfaces
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Inheritance
InheritanceInheritance
Inheritance
 
Interface
InterfaceInterface
Interface
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 

Destaque

Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
Abed Bukhari
 
Chapter 7 - Data Link Control Protocols 9e
Chapter 7 - Data Link Control Protocols 9eChapter 7 - Data Link Control Protocols 9e
Chapter 7 - Data Link Control Protocols 9e
adpeer
 

Destaque (15)

C# basics training (Inheritance)
C# basics training (Inheritance)C# basics training (Inheritance)
C# basics training (Inheritance)
 
Inheritance in C#
Inheritance in C#Inheritance in C#
Inheritance in C#
 
Classes2
Classes2Classes2
Classes2
 
Xamarin: Branching and Looping
Xamarin: Branching and LoopingXamarin: Branching and Looping
Xamarin: Branching and Looping
 
Introduction of C#
Introduction of C#Introduction of C#
Introduction of C#
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
 
interface in c#
interface in c#interface in c#
interface in c#
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
C#.NET
C#.NETC#.NET
C#.NET
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type Conversion
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter 7 - Data Link Control Protocols 9e
Chapter 7 - Data Link Control Protocols 9eChapter 7 - Data Link Control Protocols 9e
Chapter 7 - Data Link Control Protocols 9e
 
Xamarin - First Application
Xamarin - First ApplicationXamarin - First Application
Xamarin - First Application
 
Learn C# programming - Program Structure & Basic Syntax
Learn C# programming - Program Structure & Basic SyntaxLearn C# programming - Program Structure & Basic Syntax
Learn C# programming - Program Structure & Basic Syntax
 

Semelhante a Xamarin: Inheritance and Polymorphism

Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
JP2B1197685ARamSaiPM
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
Mohamed Essam
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
SURBHI SAROHA
 

Semelhante a Xamarin: Inheritance and Polymorphism (20)

Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
Inheritance and Polymorphism in Oops
Inheritance and Polymorphism in OopsInheritance and Polymorphism in Oops
Inheritance and Polymorphism in Oops
 
Ritik (inheritance.cpp)
Ritik (inheritance.cpp)Ritik (inheritance.cpp)
Ritik (inheritance.cpp)
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Inheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan PasrichaInheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan Pasricha
 
Inheritance (with classifications)
Inheritance (with classifications)Inheritance (with classifications)
Inheritance (with classifications)
 
C plusplus
C plusplusC plusplus
C plusplus
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
C++
C++C++
C++
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
 

Mais de Eng Teong Cheah

Mais de Eng Teong Cheah (20)

Monitoring Models
Monitoring ModelsMonitoring Models
Monitoring Models
 
Responsible Machine Learning
Responsible Machine LearningResponsible Machine Learning
Responsible Machine Learning
 
Training Optimal Models
Training Optimal ModelsTraining Optimal Models
Training Optimal Models
 
Deploying Models
Deploying ModelsDeploying Models
Deploying Models
 
Machine Learning Workflows
Machine Learning WorkflowsMachine Learning Workflows
Machine Learning Workflows
 
Working with Compute
Working with ComputeWorking with Compute
Working with Compute
 
Working with Data
Working with DataWorking with Data
Working with Data
 
Experiments & TrainingModels
Experiments & TrainingModelsExperiments & TrainingModels
Experiments & TrainingModels
 
Automated Machine Learning
Automated Machine LearningAutomated Machine Learning
Automated Machine Learning
 
Getting Started with Azure Machine Learning
Getting Started with Azure Machine LearningGetting Started with Azure Machine Learning
Getting Started with Azure Machine Learning
 
Hacking Containers - Container Storage
Hacking Containers - Container StorageHacking Containers - Container Storage
Hacking Containers - Container Storage
 
Hacking Containers - Looking at Cgroups
Hacking Containers - Looking at CgroupsHacking Containers - Looking at Cgroups
Hacking Containers - Looking at Cgroups
 
Hacking Containers - Linux Containers
Hacking Containers - Linux ContainersHacking Containers - Linux Containers
Hacking Containers - Linux Containers
 
Data Security - Storage Security
Data Security - Storage SecurityData Security - Storage Security
Data Security - Storage Security
 
Application Security- App security
Application Security- App securityApplication Security- App security
Application Security- App security
 
Application Security - Key Vault
Application Security - Key VaultApplication Security - Key Vault
Application Security - Key Vault
 
Compute Security - Container Security
Compute Security - Container SecurityCompute Security - Container Security
Compute Security - Container Security
 
Compute Security - Host Security
Compute Security - Host SecurityCompute Security - Host Security
Compute Security - Host Security
 
Virtual Networking Security - Network Security
Virtual Networking Security - Network SecurityVirtual Networking Security - Network Security
Virtual Networking Security - Network Security
 
Virtual Networking Security - Perimeter Security
Virtual Networking Security - Perimeter SecurityVirtual Networking Security - Perimeter Security
Virtual Networking Security - Perimeter Security
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Xamarin: Inheritance and Polymorphism

  • 1. Inheritance & Polymorphism Eng Teong Cheah Microsoft MVP Windows Development
  • 3. Inheritance C# is an object oriented programming language so it supports one key feature of OOPS; Inheritance. In general, Inheritance can be explained as acquiring the properties of the parent. For this, we will use the most common example of the car class. You can see Car is an Object who has basic feature like name, height, no of wheels. It has two specialized version one is sedan and other is hatchback. Both sedan and hatch back has all the basic feature of car and some specialized property of their own. This feature is known as inheritance.
  • 4. Inheritance When a child class has all the features of base class plus its own specialized properties. Then this phenomenon is known as inheritance.
  • 5. Inheritance Types of inheritance supported by C# are follows: - Single inheritance Single base class and single derived class. - Multilevel inheritance B derive from A and C derive from B. - Hierarchical inheritance B and C both derived from A. - Multiple inheritance using Interfaces Class D derived from Interface A, Interface B and Class C.
  • 6. Inheritance Preventing a Class from Being Inherited C# We can prevent the class from Being Inherited by Other Class by putting Sealed Keyword in class. See Example Below:- sealed class stringHandler { public string inputString { get; set; } public string OutputString { get; set; } public stringHandler(string inputstring) { this.inputString = inputString; } public String FormatString() { // Some Code here } }
  • 7. Inheritance Constructor initialization C# Inheritance See the car example on top of this page, if we create an object of HatchBack class . The constructor initialization series is given below – HatchBack hb = new HatchBack("hatchback",4,125,40,true); 1. First Car constructor is initialized public Car(string name, int wheelcount, float length, float breadth) { this.Name = name; this.WheelCount = wheelcount; this.length = length; this.breadth = breadth; }
  • 8. Inheritance 2. Second Hatchback Constructor will be initialized public HatchBack(string name, int wheelcount, float length, float breadth, bool isconvertible) : base(name, wheelcount, length, breadth) { this.IsConvertible = isconvertible; } So, from these examples we can say that constructor initialization in inheritance will always follow from base to derived downwards.
  • 9. Inheritance Calling Base class’s Constructor in Inherited C# Classes : Base class constructor is called in derived class using base Keyword. See Car example on top of the page Calling a Base class’s Hidden members in inherited class C# : Base class hidden member function can be called by using base.functionname syntax. See Example below -
  • 10. Inheritance Type Casting in Inheritance C# Parent class reference can hold child class reference but opposite is not true. Casting an object to a parent class is called upcasting. Casting an object to child class is called downcasting. See Example below - We have Draw() method both in base class and derived class. But the see which one is called when. If the Shape class’s Draw() Method is declared as virtual and overridden in Oval class’s Draw() method then result would be different. Result would be. Output when Draw() method will be declared as Virtual and overridden in derived class : Shape Drawn Oval Drawn Oval Drawn
  • 12. Polymorphism Polymorphism is one of the key features of OOPS. Polymorphism can be broken as below. Polymorphism =Poly + morphism =Multiple + forms. Polymorphism is simply calling derived class methods from base class reference during runtime. It is the behavioural change of methods depending upon the instance called at runtime.
  • 13. Polymorphism Before we understand it in polymorphism in C# language, let’s understand it with a simple fantasy example. A mermaid, yes a mermaid. Viola……But how a mermaid is related to Polymorphism see image below. Mermaid shows a polymorphic behavior according to environment. Mermaid behaves like human while on earth and as a fish while in water.
  • 14. Example Class Hierarchy Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
  • 15. Inherited Methods A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
  • 16. Inherited Methods The method Foo() can be overridden in classes B and C:
  • 17. Inherited Methods There are two problems with this code. - The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section. - Although the code compiles and runs, the compiler produces a warning: ...polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()' This issue will be discussed in section Hiding and Overriding Methods.
  • 18. Virtual and Overridden Methods Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
  • 19. Method Hiding Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
  • 20. Combining Method Overriding and Hiding Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
  • 21. Combining Method Overriding and Hiding A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
  • 22. Demo