SlideShare a Scribd company logo
1 of 11
C#
LECTURE#11
Abid Kohistani
GC Madyan Swat
polymorphism
The word polymorphism means having many forms.
In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic.
 In static polymorphism, the response to a function is determined at the compile time.
 In dynamic polymorphism, it is decided at run-time.
Static Polymorphism:
The mechanism of linking a function with an object during compile time is called early binding. It is
also called static binding. C# provides two techniques to implement static polymorphism. They are:
Function overloading
Operator overloading
Function Overloading
You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the number of arguments in the
argument list.
You cannot overload function declarations that differ only by return type.
Example
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int i) {
Console.WriteLine("Printing int: {0}", i );
}
void print(double f) {
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s) {
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{ Printdata p = new Printdata(); // Call print to print integer
p.print(5); // Call print to print float
p.print(500.263); // Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation of an interface.
Implementation is completed when a derived class inherits from it.
Abstract classes contain abstract methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
Here are the rules about abstract classes:
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract class
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
The following program demonstrates an abstract class
Example
using System;
namespace PolymorphismApplication
{
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape
{
private int length;
private int width;
public Rectangle( int a = 0, int b = 0)
{
length = a; width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args)
{ Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
Example
Example explained
The output from the example above was probably
not what you expected. That is because the base
class method overrides the derived class method,
when they share the same name.
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child) {
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child) {
public void animalSound() {
Console.WriteLine("The dog says: bow wow");
}
}
class Program {
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound(); } }
The animal makes a sound
The animal makes a sound
The animal makes a sound
output
Example 2
Example explained
However, C# provides an option to override the
base class method, by adding the virtual keyword
to the method inside the base class, and by using
the override keyword for each derived class
methods:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
output
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
} }
class Pig : Animal // Derived class (child)
{
public override void animalSound() {
Console.WriteLine("The pig says: wee wee");
} }
class Dog : Animal // Derived class (child) {
public override void animalSound() {
Console.WriteLine("The dog says: bow wow"); } }
class Program {
static void Main(string[] args) {
Animal myAnimal = new Animal(); // Create a Animal
object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
} }
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces
The abstract keyword is used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by
the derived class (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
} }
Example From the example above, it is not possible to
create an object of the Animal class:
Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class
Abstract Classes and Methods
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in
the Polymorphism chapter to an abstract class.
Remember from the Inheritance chapter that we use the : symbol to inherit from a class, and that we use the
override keyword to override the base class method.
Example
Example
// Abstract class
abstract class Animal
{ // Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig();// Create a Pig object
myPig.animalSound();// Call the abstract method
myPig.sleep(); // Call the regular method
} }
Why And When To Use Abstract Classes
and Methods?
To achieve security - hide certain details
and only show the important details of
an object.
END

More Related Content

What's hot (20)

Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
C# operators
C# operatorsC# operators
C# operators
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
polymorphism ppt
polymorphism pptpolymorphism ppt
polymorphism ppt
 
Interface
InterfaceInterface
Interface
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Inheritance
InheritanceInheritance
Inheritance
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 

Similar to Polymorphism in C# Function overloading in C#

Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interfaceShubham Sharma
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3Narayana Swamy
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismAndiNurkholis1
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfBapanKar2
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppthenokmetaferia1
 

Similar to Polymorphism in C# Function overloading in C# (20)

Inheritance
InheritanceInheritance
Inheritance
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3
 
Only oop
Only oopOnly oop
Only oop
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 

More from Abid Kohistani

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and NotationsAbid Kohistani
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAbid Kohistani
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.Abid Kohistani
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Abid Kohistani
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-SharpAbid Kohistani
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)Abid Kohistani
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)Abid Kohistani
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Abid Kohistani
 

More from Abid Kohistani (9)

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and Notations
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and Encapsulation
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 

Recently uploaded

JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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 educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Polymorphism in C# Function overloading in C#

  • 2. polymorphism The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. Polymorphism can be static or dynamic.  In static polymorphism, the response to a function is determined at the compile time.  In dynamic polymorphism, it is decided at run-time. Static Polymorphism: The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are: Function overloading Operator overloading
  • 3. Function Overloading You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. Example using System; namespace PolymorphismApplication { class Printdata { void print(int i) { Console.WriteLine("Printing int: {0}", i ); } void print(double f) { Console.WriteLine("Printing float: {0}" , f); } void print(string s) { Console.WriteLine("Printing string: {0}", s); } static void Main(string[] args) { Printdata p = new Printdata(); // Call print to print integer p.print(5); // Call print to print float p.print(500.263); // Call print to print string p.print("Hello C++"); Console.ReadKey(); } } }
  • 4. Dynamic Polymorphism C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. Here are the rules about abstract classes: You cannot create an instance of an abstract class You cannot declare an abstract method outside an abstract class When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
  • 5. The following program demonstrates an abstract class Example using System; namespace PolymorphismApplication { abstract class Shape { public abstract int area(); } class Rectangle: Shape { private int length; private int width; public Rectangle( int a = 0, int b = 0) { length = a; width = b; } public override int area () { Console.WriteLine("Rectangle class area :"); return (width * length); } } class RectangleTester { static void Main(string[] args) { Rectangle r = new Rectangle(10, 7); double a = r.area(); Console.WriteLine("Area: {0}",a); Console.ReadKey(); } } }
  • 6. Example Example explained The output from the example above was probably not what you expected. That is because the base class method overrides the derived class method, when they share the same name. class Animal // Base class (parent) { public void animalSound() { Console.WriteLine("The animal makes a sound"); } } class Pig : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The pig says: wee wee"); } } class Dog : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The dog says: bow wow"); } } class Program { static void Main(string[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } } The animal makes a sound The animal makes a sound The animal makes a sound output
  • 7. Example 2 Example explained However, C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using the override keyword for each derived class methods: The animal makes a sound The pig says: wee wee The dog says: bow wow output class Animal // Base class (parent) { public virtual void animalSound() { Console.WriteLine("The animal makes a sound"); } } class Pig : Animal // Derived class (child) { public override void animalSound() { Console.WriteLine("The pig says: wee wee"); } } class Dog : Animal // Derived class (child) { public override void animalSound() { Console.WriteLine("The dog says: bow wow"); } } class Program { static void Main(string[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } }
  • 8. Abstract Classes and Methods Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces The abstract keyword is used for classes and methods: Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from). An abstract class can have both abstract and regular methods: abstract class Animal { public abstract void animalSound(); public void sleep() { Console.WriteLine("Zzz"); } } Example From the example above, it is not possible to create an object of the Animal class: Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class
  • 9. Abstract Classes and Methods To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the Polymorphism chapter to an abstract class. Remember from the Inheritance chapter that we use the : symbol to inherit from a class, and that we use the override keyword to override the base class method.
  • 10. Example Example // Abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { Console.WriteLine("Zzz"); } } // Derived class (inherit from Animal) class Pig : Animal { public override void animalSound() { // The body of animalSound() is provided here Console.WriteLine("The pig says: wee wee"); } } class Program { static void Main(string[] args) { Pig myPig = new Pig();// Create a Pig object myPig.animalSound();// Call the abstract method myPig.sleep(); // Call the regular method } } Why And When To Use Abstract Classes and Methods? To achieve security - hide certain details and only show the important details of an object.
  • 11. END