SlideShare a Scribd company logo
Programming in C#
Inheritance and Polymorphism
CSE 459.24
Prof. Roger Crawfis
C# Classes
 Classes are used to accomplish:
 Modularity: Scope for global (static) methods
 Blueprints for generating objects or instances:
 Per instance data and method signatures
 Classes support
 Data encapsulation - private data and
implementation.
 Inheritance - code reuse
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 any one else
 Protected access available only to child classes (and their
descendants).
 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
an is-a relationship,
meaning the child is a
more specific version of
the parent.
Animal
Bird
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
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.
+ public
- private
# protected
The protected Modifier
 Variables and methods
declared with protected
visibility in a parent class
are only accessible by a
child class or any class
derived from that class
Book
# pages : int
+ GetNumberOfPages() : void
Dictionary
- definition : int
+ PrintDefinitionMessage() : void
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.
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.
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 Bat
Horse
Parrot
Class Hierarchies
CommunityMember
Employee Student Alumnus
Faculty Staff
Professor Instructor
Graduate
Under
Class Hierarchies
Shape
TwoDimensionalShape ThreeDimensionalShape
Sphere Cube Cylinder
Triangle
Square
Circle
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 Christmas, then a
Holiday reference can be used to point to a
Christmas object. Holiday day;
day = new Holiday();
…
day = new Christmas();
Dynamic Binding
A polymorphic reference is one which
can refer to different types of objects at
different times. It morphs!
The type of the actual instance, not the
declared type, determines which method
is invoked.
Polymorphic references are therefore
resolved at run-time, not during
compilation.
 This is called dynamic binding.
Dynamic Binding
Suppose the Holiday class has a method
called Celebrate, and the Christmas
class redefines it (overrides it).
Now consider the following invocation:
day.Celebrate();
If day refers to a Holiday object, it
invokes the Holiday version of
Celebrate; if it refers to a Christmas
object, it invokes the Christmas version
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
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() {}}
Polymorphism via Inheritance
StaffMember
# name : string
# address : string
# phone : string
+ ToString() : string
+ Pay() : double
Volunteer
+ Pay() : double
Employee
# socialSecurityNumber : String
# payRate : double
+ ToString() : string
+ Pay() : double
Executive
- bonus : double
+ AwardBonus(execBonus : double) : void
+ Pay() : double
Hourly
- hoursWorked : int
+ AddHours(moreHours : int) : void
+ ToString() : string
+ Pay() : double
Widening and Narrowing
 Assigning an object to an ancestor reference is
considered to be a widening conversion, and
can be performed by simple assignment
Holiday day = new Christmas();
 Assigning an ancestor object to a reference can
also be done, but it is considered to be a
narrowing conversion and must be done with a
cast:
Christmas christ = new Christmas();
Holiday day = christ;
Christmas christ2 = (Christmas)day;
Widening and Narrowing
 Widening conversions are most common.
 Used in polymorphism.
 Note: Do not be confused with the term widening
or narrowing and memory. Many books use short
to long as a widening conversion. A long just
happens to take-up more memory in this case.
 More accurately, think in terms of sets:
 The set of animals is greater than the set of parrots.
 The set of whole numbers between 0-65535 (ushort)
is greater (wider) than those from 0-255 (byte).
Type Unification
Everything in C# inherits from object
 Similar to Java except includes value types.
 Value types are still light-weight and handled
specially by the CLI/CLR.
 This provides a single base type for all
instances of all types.
 Called Type Unification
The System.Object Class
 All classes in C# are derived from the Object class
 if a class is not explicitly defined to be the child of an existing class, it is a
direct descendant of the Object class
 The Object class is therefore the ultimate root of all class
hierarchies.
 The Object class defines methods that will be shared by all
objects in C#, e.g.,
 ToString: converts an object to a string representation
 Equals: checks if two objects are the same
 GetType: returns the type of a type of object
 A class can override a method defined in Object to have a
different behavior, e.g.,
 String class overrides the Equals method to compare the content of two
strings

More Related Content

Similar to CSharp_03_Inheritance_introduction_with_examples (20)

Xamarin: Inheritance and Polymorphism
Xamarin: Inheritance and PolymorphismXamarin: Inheritance and Polymorphism
Xamarin: Inheritance and Polymorphism
Eng Teong Cheah
 
Opps
OppsOpps
Opps
Lalit Kale
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Object
ObjectObject
Object
Mohammad Mahdi Rahimi Moghadam
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 
L5
L5L5
L5
lksoo
 
Unit 3
Unit 3Unit 3
Unit 3
R S S RAJU BATTULA
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
OOPS – General Understanding in .NET
OOPS – General Understanding in .NETOOPS – General Understanding in .NET
OOPS – General Understanding in .NET
Sabith Byari
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Unusual C# - OOP
Unusual C# - OOPUnusual C# - OOP
Unusual C# - OOP
Medhat Dawoud
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdf
PavanNarne1
 
29csharp
29csharp29csharp
29csharp
Sireesh K
 
29c
29c29c
29c
Sireesh K
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
DurgaPrasadVasantati
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
DurgaPrasadVasantati
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Oops
OopsOops
Oops
Sankar Balasubramanian
 
Unit2_4.pptx Object Oriented Concepts .
Unit2_4.pptx  Object Oriented Concepts .Unit2_4.pptx  Object Oriented Concepts .
Unit2_4.pptx Object Oriented Concepts .
Priyanka Jadhav
 
Classes2
Classes2Classes2
Classes2
phanleson
 

More from Ranjithsingh20 (9)

Chapter-11 - OS-windows and its generations
Chapter-11 - OS-windows and its generationsChapter-11 - OS-windows and its generations
Chapter-11 - OS-windows and its generations
Ranjithsingh20
 
OS_Chapter-12 simple concepts and design
OS_Chapter-12 simple concepts and designOS_Chapter-12 simple concepts and design
OS_Chapter-12 simple concepts and design
Ranjithsingh20
 
CSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examplesCSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examples
Ranjithsingh20
 
CSharp_03_Properties_introductionwithexamples
CSharp_03_Properties_introductionwithexamplesCSharp_03_Properties_introductionwithexamples
CSharp_03_Properties_introductionwithexamples
Ranjithsingh20
 
CSharp_03_Generics_introduction_withexamples
CSharp_03_Generics_introduction_withexamplesCSharp_03_Generics_introduction_withexamples
CSharp_03_Generics_introduction_withexamples
Ranjithsingh20
 
CSharp_03_ClassesStructs_and_introduction
CSharp_03_ClassesStructs_and_introductionCSharp_03_ClassesStructs_and_introduction
CSharp_03_ClassesStructs_and_introduction
Ranjithsingh20
 
CSharp_02_LanguageOverview_andintroduction
CSharp_02_LanguageOverview_andintroductionCSharp_02_LanguageOverview_andintroduction
CSharp_02_LanguageOverview_andintroduction
Ranjithsingh20
 
CSharp_02_Arrays_fundamentals_concepts_introduction
CSharp_02_Arrays_fundamentals_concepts_introductionCSharp_02_Arrays_fundamentals_concepts_introduction
CSharp_02_Arrays_fundamentals_concepts_introduction
Ranjithsingh20
 
CSharp_01_CLROverview_and Introductionc#
CSharp_01_CLROverview_and Introductionc#CSharp_01_CLROverview_and Introductionc#
CSharp_01_CLROverview_and Introductionc#
Ranjithsingh20
 
Chapter-11 - OS-windows and its generations
Chapter-11 - OS-windows and its generationsChapter-11 - OS-windows and its generations
Chapter-11 - OS-windows and its generations
Ranjithsingh20
 
OS_Chapter-12 simple concepts and design
OS_Chapter-12 simple concepts and designOS_Chapter-12 simple concepts and design
OS_Chapter-12 simple concepts and design
Ranjithsingh20
 
CSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examplesCSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examples
Ranjithsingh20
 
CSharp_03_Properties_introductionwithexamples
CSharp_03_Properties_introductionwithexamplesCSharp_03_Properties_introductionwithexamples
CSharp_03_Properties_introductionwithexamples
Ranjithsingh20
 
CSharp_03_Generics_introduction_withexamples
CSharp_03_Generics_introduction_withexamplesCSharp_03_Generics_introduction_withexamples
CSharp_03_Generics_introduction_withexamples
Ranjithsingh20
 
CSharp_03_ClassesStructs_and_introduction
CSharp_03_ClassesStructs_and_introductionCSharp_03_ClassesStructs_and_introduction
CSharp_03_ClassesStructs_and_introduction
Ranjithsingh20
 
CSharp_02_LanguageOverview_andintroduction
CSharp_02_LanguageOverview_andintroductionCSharp_02_LanguageOverview_andintroduction
CSharp_02_LanguageOverview_andintroduction
Ranjithsingh20
 
CSharp_02_Arrays_fundamentals_concepts_introduction
CSharp_02_Arrays_fundamentals_concepts_introductionCSharp_02_Arrays_fundamentals_concepts_introduction
CSharp_02_Arrays_fundamentals_concepts_introduction
Ranjithsingh20
 
CSharp_01_CLROverview_and Introductionc#
CSharp_01_CLROverview_and Introductionc#CSharp_01_CLROverview_and Introductionc#
CSharp_01_CLROverview_and Introductionc#
Ranjithsingh20
 
Ad

Recently uploaded (20)

Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Ad

CSharp_03_Inheritance_introduction_with_examples

  • 1. Programming in C# Inheritance and Polymorphism CSE 459.24 Prof. Roger Crawfis
  • 2. C# Classes  Classes are used to accomplish:  Modularity: Scope for global (static) methods  Blueprints for generating objects or instances:  Per instance data and method signatures  Classes support  Data encapsulation - private data and implementation.  Inheritance - code reuse
  • 3. 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 any one else  Protected access available only to child classes (and their descendants).  The child has its own unique behaviors and data.
  • 4. Inheritance  Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class.  Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent. Animal Bird
  • 5. 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
  • 6. Declaring a Derived Class  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }
  • 7. 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.
  • 8. + public - private # protected The protected Modifier  Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class Book # pages : int + GetNumberOfPages() : void Dictionary - definition : int + PrintDefinitionMessage() : void
  • 9. 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.
  • 10. 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.
  • 11. 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 Bat Horse Parrot
  • 12. Class Hierarchies CommunityMember Employee Student Alumnus Faculty Staff Professor Instructor Graduate Under
  • 14. 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.
  • 15. 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 Christmas, then a Holiday reference can be used to point to a Christmas object. Holiday day; day = new Holiday(); … day = new Christmas();
  • 16. Dynamic Binding A polymorphic reference is one which can refer to different types of objects at different times. It morphs! The type of the actual instance, not the declared type, determines which method is invoked. Polymorphic references are therefore resolved at run-time, not during compilation.  This is called dynamic binding.
  • 17. Dynamic Binding Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it). Now consider the following invocation: day.Celebrate(); If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version
  • 18. 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.
  • 19. 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.
  • 20. 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() {}}
  • 21. Polymorphism via Inheritance StaffMember # name : string # address : string # phone : string + ToString() : string + Pay() : double Volunteer + Pay() : double Employee # socialSecurityNumber : String # payRate : double + ToString() : string + Pay() : double Executive - bonus : double + AwardBonus(execBonus : double) : void + Pay() : double Hourly - hoursWorked : int + AddHours(moreHours : int) : void + ToString() : string + Pay() : double
  • 22. Widening and Narrowing  Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment Holiday day = new Christmas();  Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast: Christmas christ = new Christmas(); Holiday day = christ; Christmas christ2 = (Christmas)day;
  • 23. Widening and Narrowing  Widening conversions are most common.  Used in polymorphism.  Note: Do not be confused with the term widening or narrowing and memory. Many books use short to long as a widening conversion. A long just happens to take-up more memory in this case.  More accurately, think in terms of sets:  The set of animals is greater than the set of parrots.  The set of whole numbers between 0-65535 (ushort) is greater (wider) than those from 0-255 (byte).
  • 24. Type Unification Everything in C# inherits from object  Similar to Java except includes value types.  Value types are still light-weight and handled specially by the CLI/CLR.  This provides a single base type for all instances of all types.  Called Type Unification
  • 25. The System.Object Class  All classes in C# are derived from the Object class  if a class is not explicitly defined to be the child of an existing class, it is a direct descendant of the Object class  The Object class is therefore the ultimate root of all class hierarchies.  The Object class defines methods that will be shared by all objects in C#, e.g.,  ToString: converts an object to a string representation  Equals: checks if two objects are the same  GetType: returns the type of a type of object  A class can override a method defined in Object to have a different behavior, e.g.,  String class overrides the Equals method to compare the content of two strings