SlideShare a Scribd company logo
Programming in C#
Inheritance and Polymorphism
Renas R. Rekany
2018
Inheritance
▪ Inheritance allows a software developer to derive a new
class from an existing one.
▪ The existing class is called the parent, super, or base class.
▪ The derived class is called a child or subclass.
▪ The child inherits characteristics of the parent.
▪ Methods and data defined for the parent class.
▪ The child has special rights to the parents methods and data.
▪ Public access like anyone else
▪ Protected access available only to child classes.
▪ The child has its own unique behaviors and data.
Inheritance
▪ Inheritance relationships
are often shown
graphically in a class
diagram, with the arrow
pointing to the parent
class.
▪ Inheritance should create a
relationship, meaning the
child is a more specific
version of the parent.
Animal
Bird
Declaring a Derived Class
▪ Define a new class DerivedClass which extends
BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
Controlling Inheritance
▪ A child class inherits the methods and data defined for the
parent class; however, whether a data or method member of
a parent class is accessible in the child class depends on the
visibility modifier of a member.
▪ Variables and methods declared with private visibility are
not accessible in the child class
▪ However, a private data member defined in the parent class is still
part of the state of a derived class.
▪ Variables and methods declared with public visibility are
accessible; but public variables violate our goal of
encapsulation
▪ There is a third visibility modifier that helps in inheritance
situations: protected.
Inheritance
class color
{ public color() {MessageBox.Show("color"); }
public void fill(string s) { (Messagebox.Show(s); }
}
class green : color
{ public green() {MessageBox.Show ("green"); } }
private void button1_Click(object sender, EventArgs e)
{ green g = new green();
g.fill("red");
}
Inheritance
class animal
{ public animal() {MessageBox.Show("animal"); }
public void talk() {MessageBox.Show("animal talk"); }
public void greet() {MessageBox.Show("animal say hello"); } }
class dog : animal
{ public dog() {MessageBox.Show("dog"); }
public void sing() {MessageBox.Show("dog can sing"); } }
private void button1_Click(object sender, EventArgs e)
{ animal a = new animal();
a.talk();
a.greet();
dog d = new dog();
d.sing();
d.talk();
d.greet();
}
Notes about Inheritance
➢ Constructor can't be inheritance, they just invoked.
➢ First call base then derived
➢ Destructor can't be inheritance they just invoked.
➢ First call derived then base
Example
➢ Calculation
Add, Sub
➢ Calculation2
Mult, Div
Calculation1
Calculation2
Inheritance
class animal
{ public animal() {MessageBox.Show("animal"); }
public void talk() {MessageBox.Show("animal talk"); }
public void greet() {MessageBox.Show("animal say hello"); }
~animal() {MessageBox.Show("animal Destructor"); } }
class dog : animal
{ public dog() {MessageBox.Show("dog"); }
public void sing() {MessageBox.Show("dog can sing"); }
~dog() {MessageBox.Show("dog Destructor"); } }
private void button1_Click(object sender, EventArgs e)
{ animal a = new animal();
a.talk();
a.greet();
dog d = new dog();
d.sing();
d.talk();
d.greet(); }
Examples:
Base Classes and Derived Classes
Examples:
Base Classes and Derived Classes
Base class Derived classes
Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingsAccount
Single Inheritance
▪ Some languages, e.g., C++, allow Multiple
inheritance, which allows a class to be
derived from two or more classes, inheriting
the members of all parents.
▪ C# and Java support single inheritance,
meaning that a derived class can have only
one parent class.
Class Hierarchies
▪ A child class of one parent can be the parent
of another child, forming a class hierarchy
Animal
Reptile Bird Mammal
Snake Lizard BatHorseParrot
Class Hierarchies
CommunityMember
Employee Student Alumnus
Faculty Staff
Professor Instructor
GraduateUnder
Class Hierarchies
Shape
TwoDimensionalShape ThreeDimensionalShape
Sphere Cube CylinderTriangleSquareCircle
Class Hierarchies
▪ An inherited member is continually passed
down the line
▪ Inheritance is transitive.
▪ Good class design puts all common features
as high in the hierarchy as is reasonable.
Avoids redundant code.
References and Inheritance
▪ An object reference can refer to an object of its
class, or to an object of any class derived from it by
inheritance.
▪ For example, if the Holiday class is used to derive a
child class called Friday, then a Holiday reference
can be used to point to a Fridayobject.
Holiday day;
day = new Holiday();
…
day = new Friday();
Executive
- bonus : double
+ AwardBonus(execBonus : double) : void
+ Pay() : double
Hourly
- hoursWorked : int
+ AddHours(moreHours : int) : void
+ ToString() : string
+ Pay() : double
Volunteer
+ Pay() : double
Employee
# socialSecurityNumber : String
# payRate : double
+ ToString() : string
+ Pay() : double
Polymorphism via Inheritance
StaffMember
# name : string
# address : string
# phone : string
+ ToString() : string
+ Pay() : double
Type of Polymorphism
 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.
 Base classes may define and implement virtual methods, and derived
classes can override them, which means they provide their own
definition and implementation. At run-time, when client code calls the
method, the CLR looks up the run-time type of the object, and invokes
that override of the virtual method. Thus in your source code you can
call a method on a base class, and cause a derived class's version of the
method to be executed.
Overriding Methods
 C# requires that all class definitions
communicate clearly their intentions.
 The keywords virtual, override and new provide
this communication.
 If a base class method is going to be overridden
it should be declared virtual.
 A derived class would then indicate that it
indeed does override the method with the
override keyword.
Overriding Methods
▪ A child class can override the definition of an
inherited method in favor of its own
▪ That is, a child can redefine a method that it
inherits from its parent
▪ The new method must have the same signature
as the parent's method, but can have a different
implementation.
▪ The type of the object executing the method
determines which version of the method is
invoked.
Overriding Methods
 If a derived class wishes to hide a method in
the parent class, it will use the new keyword.
This should be avoided.
Overloading vs. Overriding
▪ Overloading deals with
multiple methods in the
same class with the same
name but different
signatures
▪ Overloading lets you
define a similar
operation in different
ways for different data
▪ Example:
▪ int foo(string[] bar);
▪ int foo(int bar1, float a);
▪ Overriding deals with two
methods, one in a parent
class and one in a child
class, that have the same
signature
▪ Overriding lets you define
a similar operation in
different ways for different
object types
▪ Example:
▪ class Base {
▪ public virtual int foo() {}
}
▪ class Derived {
▪ public override int foo()
{}}
Example
public class Base
{
public virtual void Show()
{
MessageBox.Show("Show From Base Class.");
} }
public class Derived : Base
{
public override void Show()
{
MessageBox.Show("Show From Derived Class.");
} }

More Related Content

What's hot (20)

PDF
Ruby and DCI
Simon Courtois
 
PPTX
inheritance in C++
tayyaba nawaz
 
PPTX
Inheritance
Loy Calazan
 
PPTX
Inheritance in java
HarshitaAshwani
 
PPTX
Java Inheritance
VINOTH R
 
PDF
Java unit2
Abhishek Khune
 
PPTX
Inheritance
Tech_MX
 
PPTX
Advance OOP concepts in Python
Sujith Kumar
 
PDF
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
PPTX
Chap 3php array part 2
monikadeshmane
 
PPT
Php object orientation and classes
Kumar
 
PPTX
Object-Oriented Programming with C#
Svetlin Nakov
 
PDF
Class 7 2ciclo
Carlos Alcivar
 
PDF
Object Oriented Programming in PHP
Lorna Mitchell
 
PPTX
.NET F# Inheritance and operator overloading
DrRajeshreeKhande
 
PPTX
inheritance c++
Muraleedhar Sundararajan
 
PPTX
Python advance
Mukul Kirti Verma
 
PDF
Python unit 3 m.sc cs
KALAISELVI P
 
Ruby and DCI
Simon Courtois
 
inheritance in C++
tayyaba nawaz
 
Inheritance
Loy Calazan
 
Inheritance in java
HarshitaAshwani
 
Java Inheritance
VINOTH R
 
Java unit2
Abhishek Khune
 
Inheritance
Tech_MX
 
Advance OOP concepts in Python
Sujith Kumar
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Chap 3php array part 2
monikadeshmane
 
Php object orientation and classes
Kumar
 
Object-Oriented Programming with C#
Svetlin Nakov
 
Class 7 2ciclo
Carlos Alcivar
 
Object Oriented Programming in PHP
Lorna Mitchell
 
.NET F# Inheritance and operator overloading
DrRajeshreeKhande
 
inheritance c++
Muraleedhar Sundararajan
 
Python advance
Mukul Kirti Verma
 
Python unit 3 m.sc cs
KALAISELVI P
 

Similar to Object oriented programming inheritance (20)

PPT
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
PPTX
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
PPTX
Inheritance.pptx
PRIYACHAURASIYA25
 
PDF
Xamarin: Inheritance and Polymorphism
Eng Teong Cheah
 
PPT
20 Object-oriented programming principles
maznabili
 
PPTX
SAD04 - Inheritance
Michael Heron
 
DOCX
Ganesh groups
Ganesh Amirineni
 
PPT
Opps
Lalit Kale
 
PPTX
Object oriented programming Fundamental Concepts
Bharat Kalia
 
PPT
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
PDF
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Akhil Mittal
 
PPT
Unit 7 inheritance
atcnerd
 
PDF
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Akhil Mittal
 
ODP
Ppt of c++ vs c#
shubhra chauhan
 
PPTX
29csharp
Sireesh K
 
PPTX
29c
Sireesh K
 
PPT
Inheritance
abhay singh
 
PPTX
Core java oop
Parth Shah
 
PPTX
Object Oriented Programming C#
Muhammad Younis
 
PPTX
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
Inheritance.pptx
PRIYACHAURASIYA25
 
Xamarin: Inheritance and Polymorphism
Eng Teong Cheah
 
20 Object-oriented programming principles
maznabili
 
SAD04 - Inheritance
Michael Heron
 
Ganesh groups
Ganesh Amirineni
 
Object oriented programming Fundamental Concepts
Bharat Kalia
 
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Akhil Mittal
 
Unit 7 inheritance
atcnerd
 
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Akhil Mittal
 
Ppt of c++ vs c#
shubhra chauhan
 
29csharp
Sireesh K
 
Inheritance
abhay singh
 
Core java oop
Parth Shah
 
Object Oriented Programming C#
Muhammad Younis
 
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Ad

More from Renas Rekany (20)

PDF
decision making
Renas Rekany
 
PDF
Artificial Neural Network
Renas Rekany
 
PDF
AI heuristic search
Renas Rekany
 
PDF
AI local search
Renas Rekany
 
PDF
AI simple search strategies
Renas Rekany
 
PDF
C# p9
Renas Rekany
 
PDF
C# p8
Renas Rekany
 
PDF
C# p7
Renas Rekany
 
PDF
C# p6
Renas Rekany
 
PDF
C# p5
Renas Rekany
 
PDF
C# p4
Renas Rekany
 
PDF
C# p3
Renas Rekany
 
PDF
C# p2
Renas Rekany
 
PDF
C# p1
Renas Rekany
 
PDF
C# with Renas
Renas Rekany
 
PDF
Object oriented programming
Renas Rekany
 
PDF
Renas Rajab Asaad
Renas Rekany
 
PDF
Renas Rajab Asaad
Renas Rekany
 
PDF
Renas Rajab Asaad
Renas Rekany
 
PDF
Renas Rajab Asaad
Renas Rekany
 
decision making
Renas Rekany
 
Artificial Neural Network
Renas Rekany
 
AI heuristic search
Renas Rekany
 
AI local search
Renas Rekany
 
AI simple search strategies
Renas Rekany
 
C# with Renas
Renas Rekany
 
Object oriented programming
Renas Rekany
 
Renas Rajab Asaad
Renas Rekany
 
Renas Rajab Asaad
Renas Rekany
 
Renas Rajab Asaad
Renas Rekany
 
Renas Rajab Asaad
Renas Rekany
 
Ad

Recently uploaded (20)

PPTX
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PPTX
MATH 8 QUARTER 1 WEEK 1 LESSON 2 PRESENTATION
JohnGuillerNestalBah1
 
PPTX
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
PPTX
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
PPTX
grade 8 week 2 ict.pptx. matatag grade 7
VanessaTaberlo
 
PDF
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
PPTX
ENGLISH 8 REVISED K-12 CURRICULUM QUARTER 1 WEEK 1
LeomarrYsraelArzadon
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PDF
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
MATH 8 QUARTER 1 WEEK 1 LESSON 2 PRESENTATION
JohnGuillerNestalBah1
 
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
grade 8 week 2 ict.pptx. matatag grade 7
VanessaTaberlo
 
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
ENGLISH 8 REVISED K-12 CURRICULUM QUARTER 1 WEEK 1
LeomarrYsraelArzadon
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 

Object oriented programming inheritance

  • 1. Programming in C# Inheritance and Polymorphism Renas R. Rekany 2018
  • 2. Inheritance ▪ Inheritance allows a software developer to derive a new class from an existing one. ▪ The existing class is called the parent, super, or base class. ▪ The derived class is called a child or subclass. ▪ The child inherits characteristics of the parent. ▪ Methods and data defined for the parent class. ▪ The child has special rights to the parents methods and data. ▪ Public access like anyone else ▪ Protected access available only to child classes. ▪ The child has its own unique behaviors and data.
  • 3. Inheritance ▪ Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class. ▪ Inheritance should create a relationship, meaning the child is a more specific version of the parent. Animal Bird
  • 4. Declaring a Derived Class ▪ Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }
  • 5. Controlling Inheritance ▪ A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member. ▪ Variables and methods declared with private visibility are not accessible in the child class ▪ However, a private data member defined in the parent class is still part of the state of a derived class. ▪ Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation ▪ There is a third visibility modifier that helps in inheritance situations: protected.
  • 6. Inheritance class color { public color() {MessageBox.Show("color"); } public void fill(string s) { (Messagebox.Show(s); } } class green : color { public green() {MessageBox.Show ("green"); } } private void button1_Click(object sender, EventArgs e) { green g = new green(); g.fill("red"); }
  • 7. Inheritance class animal { public animal() {MessageBox.Show("animal"); } public void talk() {MessageBox.Show("animal talk"); } public void greet() {MessageBox.Show("animal say hello"); } } class dog : animal { public dog() {MessageBox.Show("dog"); } public void sing() {MessageBox.Show("dog can sing"); } } private void button1_Click(object sender, EventArgs e) { animal a = new animal(); a.talk(); a.greet(); dog d = new dog(); d.sing(); d.talk(); d.greet(); }
  • 8. Notes about Inheritance ➢ Constructor can't be inheritance, they just invoked. ➢ First call base then derived ➢ Destructor can't be inheritance they just invoked. ➢ First call derived then base
  • 9. Example ➢ Calculation Add, Sub ➢ Calculation2 Mult, Div Calculation1 Calculation2
  • 10. Inheritance class animal { public animal() {MessageBox.Show("animal"); } public void talk() {MessageBox.Show("animal talk"); } public void greet() {MessageBox.Show("animal say hello"); } ~animal() {MessageBox.Show("animal Destructor"); } } class dog : animal { public dog() {MessageBox.Show("dog"); } public void sing() {MessageBox.Show("dog can sing"); } ~dog() {MessageBox.Show("dog Destructor"); } } private void button1_Click(object sender, EventArgs e) { animal a = new animal(); a.talk(); a.greet(); dog d = new dog(); d.sing(); d.talk(); d.greet(); }
  • 11. Examples: Base Classes and Derived Classes
  • 12. Examples: Base Classes and Derived Classes Base class Derived classes Student GraduateStudent UndergraduateStudent Shape Circle Triangle Rectangle Loan CarLoan HomeImprovementLoan MortgageLoan Employee FacultyMember StaffMember Account CheckingAccount SavingsAccount
  • 13. Single Inheritance ▪ Some languages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents. ▪ C# and Java support single inheritance, meaning that a derived class can have only one parent class.
  • 14. Class Hierarchies ▪ A child class of one parent can be the parent of another child, forming a class hierarchy Animal Reptile Bird Mammal Snake Lizard BatHorseParrot
  • 15. Class Hierarchies CommunityMember Employee Student Alumnus Faculty Staff Professor Instructor GraduateUnder
  • 17. Class Hierarchies ▪ An inherited member is continually passed down the line ▪ Inheritance is transitive. ▪ Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.
  • 18. References and Inheritance ▪ An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance. ▪ For example, if the Holiday class is used to derive a child class called Friday, then a Holiday reference can be used to point to a Fridayobject. Holiday day; day = new Holiday(); … day = new Friday();
  • 19. Executive - bonus : double + AwardBonus(execBonus : double) : void + Pay() : double Hourly - hoursWorked : int + AddHours(moreHours : int) : void + ToString() : string + Pay() : double Volunteer + Pay() : double Employee # socialSecurityNumber : String # payRate : double + ToString() : string + Pay() : double Polymorphism via Inheritance StaffMember # name : string # address : string # phone : string + ToString() : string + Pay() : double
  • 20. Type of Polymorphism  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.  Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.
  • 21. Overriding Methods  C# requires that all class definitions communicate clearly their intentions.  The keywords virtual, override and new provide this communication.  If a base class method is going to be overridden it should be declared virtual.  A derived class would then indicate that it indeed does override the method with the override keyword.
  • 22. Overriding Methods ▪ A child class can override the definition of an inherited method in favor of its own ▪ That is, a child can redefine a method that it inherits from its parent ▪ The new method must have the same signature as the parent's method, but can have a different implementation. ▪ The type of the object executing the method determines which version of the method is invoked.
  • 23. Overriding Methods  If a derived class wishes to hide a method in the parent class, it will use the new keyword. This should be avoided.
  • 24. Overloading vs. Overriding ▪ Overloading deals with multiple methods in the same class with the same name but different signatures ▪ Overloading lets you define a similar operation in different ways for different data ▪ Example: ▪ int foo(string[] bar); ▪ int foo(int bar1, float a); ▪ Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature ▪ Overriding lets you define a similar operation in different ways for different object types ▪ Example: ▪ class Base { ▪ public virtual int foo() {} } ▪ class Derived { ▪ public override int foo() {}}
  • 25. Example public class Base { public virtual void Show() { MessageBox.Show("Show From Base Class."); } } public class Derived : Base { public override void Show() { MessageBox.Show("Show From Derived Class."); } }