SlideShare a Scribd company logo
2
Most read
8
Most read
10
Most read
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)

PPTX
Getters_And_Setters.pptx
Kavindu Sachinthe
 
PPTX
Inner classes in java
PhD Research Scholar
 
PPT
OOP in C++
ppd1961
 
PPTX
Functions in c language
tanmaymodi4
 
PPTX
Functions in c
sunila tharagaturi
 
PPT
C++ oop
Sunil OS
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPT
Characteristics of c#
Prasanna Kumar SM
 
ODP
OOP java
xball977
 
PPTX
Encapsulation C++
Hashim Hashim
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPT
Introduction to c#
OpenSource Technologies Pvt. Ltd.
 
PPT
Java interfaces
Raja Sekhar
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
PDF
Character Array and String
Tasnima Hamid
 
PPTX
Data types in c++
Venkata.Manish Reddy
 
PPT
Methods in C#
Prasanna Kumar SM
 
PPTX
Java Method, Static Block
Infoviaan Technologies
 
PPTX
Unit 6. Arrays
Ashim Lamichhane
 
Getters_And_Setters.pptx
Kavindu Sachinthe
 
Inner classes in java
PhD Research Scholar
 
OOP in C++
ppd1961
 
Functions in c language
tanmaymodi4
 
Functions in c
sunila tharagaturi
 
C++ oop
Sunil OS
 
Pointer in C++
Mauryasuraj98
 
Characteristics of c#
Prasanna Kumar SM
 
OOP java
xball977
 
Encapsulation C++
Hashim Hashim
 
Classes, objects in JAVA
Abhilash Nair
 
Java interfaces
Raja Sekhar
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Character Array and String
Tasnima Hamid
 
Data types in c++
Venkata.Manish Reddy
 
Methods in C#
Prasanna Kumar SM
 
Java Method, Static Block
Infoviaan Technologies
 
Unit 6. Arrays
Ashim Lamichhane
 

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

PDF
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Akhil Mittal
 
PPT
Opps
Lalit Kale
 
PDF
Polymorphism, Abstarct Class and Interface in C#
Umar Farooq
 
PDF
Xamarin: Inheritance and Polymorphism
Eng Teong Cheah
 
PDF
Learn C# Programming Polymorphism & Operator Overloading
Eng Teong Cheah
 
PDF
Object oriented programming inheritance
Renas Rekany
 
PPTX
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
PDF
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Akhil Mittal
 
PPTX
Presentation.pptx
PavanKumar823345
 
PPT
Inheritance
abhay singh
 
PPTX
Abstract class and Interface
Haris Bin Zahid
 
PPTX
Inheritance.pptx
PRIYACHAURASIYA25
 
PPT
An Introduction to C# and .NET Framework (Basic)
Khubaib Ahmad Kunjahi
 
PPTX
Abstraction1
zindadili
 
PPT
Inheritance & Polymorphism - 2
PRN USM
 
PPTX
28csharp
Sireesh K
 
PPTX
28c
Sireesh K
 
PPT
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Akhil Mittal
 
Polymorphism, Abstarct Class and Interface in C#
Umar Farooq
 
Xamarin: Inheritance and Polymorphism
Eng Teong Cheah
 
Learn C# Programming Polymorphism & Operator Overloading
Eng Teong Cheah
 
Object oriented programming inheritance
Renas Rekany
 
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Akhil Mittal
 
Presentation.pptx
PavanKumar823345
 
Inheritance
abhay singh
 
Abstract class and Interface
Haris Bin Zahid
 
Inheritance.pptx
PRIYACHAURASIYA25
 
An Introduction to C# and .NET Framework (Basic)
Khubaib Ahmad Kunjahi
 
Abstraction1
zindadili
 
Inheritance & Polymorphism - 2
PRN USM
 
28csharp
Sireesh K
 
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Ad

More from Abid Kohistani (9)

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

Recently uploaded (20)

DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 

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