SlideShare une entreprise Scribd logo
1  sur  27
Visual Programming
OO Programming and Inheritance
Inheritance
Inheritance allows a software developer to derive a
new class from an existing one
The existing class is called the parent class, or
superclass, or base class
The derived class is called the child class, or
subclass, or derived class.
As the name implies, the child inherits characteristics
of the parent
That is, the child class inherits the methods and data
defined for the parent class
2
Inheritance
Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Animal
# weight : int

Animal

Bird

+ GetWeight() : int

Bird

Inheritance should
create an is-a
relationship,
meaning the child
is a more specific
version of the
parent

+ Fly() : void
3
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

Fig. 9.1

Inheritance examples.

4
Declaring a Derived Class
Define a new class DerivedClass which extends BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
Base class: the “parent” class; if omitted the parent is Object
See Book.cs, Dictionary.cs, BookInheritance.cs

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

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
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
 The details of each modifier are linked on the
schedule page

Book

Example
Book.cs
Dictionary.cs
BookInheritance.cs
+ public
- private
# protected

# pages : int
+ GetNumberOfPages() : void
Dictionary
- definition : int
+ PrintDefinitionMessage() : void
7
Book.cs
using System;
namespace BookInheritance
{
/// <summary>
/// Summary description for Book.
/// </summary>

public class Book
{
protected int pages;
//---------------------------------------------------------------// Constructors
//----------------------------------------------------------------

public Book()
{
pages = 1500;
}
public Book( int pages )
{
this.pages = pages;
}

//---------------------------------------------------------------// Get the number of pages of this book.
//----------------------------------------------------------------

public int GetNumberOfPages ()
{
return pages;
}
public void PrintNumberOfPages ()
{
Console.WriteLine ("Number of pages
is: " + pages);
}
} // end of class Book
} // end of namespace

8
Dictionary.cs
using System;
namespace BookInheritance
{
/// <summary>
/// Summary description for Dictionary.
/// </summary>

public class Dictionary : Book
{
private int definitions; // number of
definitions
public Dictionary()
{
definitions = 52500;
}
public Dictionary(int definitions)
{
this.definitions =
definitions;
}

//----------------------------------------------------------------// Prints a message using both local and inherited values.
//----------------------------------------------------------------public void PrintDefinitionMessage ()
{
Console.WriteLine ( "Number of definitions: " + definitions );
Console.WriteLine ( "Average definitions per page: " +
definitions / pages );
} // end of PrintDefinitionMessages
} // end of class Dictionary
} // end of namespace

9
Book.cs
using System;
namespace BookInheritance{
class BookInheritance {
//----------------------------------------------------------------// Instantiates a derived class and invokes its inherited and
// local methods.
//----------------------------------------------------------------public static void Main (String[] args)
{
Dictionary webster = new Dictionary ();
int pages = webster.GetNumberOfPages();
// Console.WriteLine( webster.pages );
Console.WriteLine( "Number of pages is " + pages );
webster.PrintDefinitionMessage();
}
} // end of class BookInheritance
} // end of namespace

10
Calling Parent’s Constructor in a Child’s
Constructor: the base Reference
Constructors are not inherited, even though they have
public visibility
The first thing a derived class does is to call its base
class’ constructor, either explicitly or implicitly

implicitly it is the default constructor
yet we often want to use a specific constructor of the parent to
set up the "parent's part" of the object

Syntax: use base
public DerivedClass : BaseClass
{
public DerivedClass(…) : base(…)
{ // …
}
}

11
Defining Methods in the Child 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
different code in the body
The type of the object executing the method
determines which version of the method is
invoked
12
Overriding Methods: Syntax
override keyword is needed if a derivedclass method overrides a base-class method
If a base class method is going to be
overridden it should be declared virtual
Example
Thought.cs
Advice.cs
ThoughtAndAdvice.cs

13
Thought.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
class Thought
{
//---------------------------------------------------// Prints a message.
//---------------------------------------------------public virtual void Message()
{
Console.WriteLine("I feel like I'm in space ");
Console.WriteLine();
} // end of message
}
}

14
Advice.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
class Advice:Thought
{
//--------------------------------------------------------------// Prints a message. This method overrides the parent's version.
// It also invokes the parent's version explicitly using super.
//----------------------------------------------------------------public override void Message()
{
Console.WriteLine("Yor are on earth");
Console.WriteLine();
base.Message();
} // end of message
}
}

15
ThoughtandAdvice.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3{
class Program {
//----------------------------------------------------------------// Instatiates two objects a invokes the message method in each.
//----------------------------------------------------------------static void Main( string[] args )
{
Thought t = new Thought();
Advice a = new Advice();
Console.WriteLine( "parked speak: ");
t.Message();
Console.WriteLine( "dates speak: ");
a.Message();
Console.ReadLine();
}}}

16
Overloading vs. Overriding
Overloading deals with
multiple methods in the
same class with the
same name but
different signatures

Overriding deals with
two methods, one in a
parent class and one in
a child class, that have
the same signature

Overloading lets you
define a similar
operation in different
ways for different data

Overriding lets you
define a similar
operation in different
ways for different object
types
17
Single vs. Multiple 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
collisions, such as the same variable name in two
parents, are hard to resolve

Thus, C# and Java support single
inheritance, meaning that a derived class can
have only one parent class
18
Class Hierarchies
A child class of one parent can be the parent
of another child, forming a class hierarchy
Animal

Reptile

Snake

Lizard

Bird

Parrot

Mammal

Horse

Bat

19
Another Example:
Base Classes and Derived Classes
CommunityMemeber

Employee

Faculty

Professor

Fig. 9.2

Student

Staff

Under

Alumnus

Graduate

Instructor

Inheritance hierarchy for university CommunityMember.
20
Yet Another Example
Shape

TwoDimensionalShape

Circle

Fig. 9.3

Square

Triangle

ThreeDimensionalShape

Sphere

Cube

Cylinder

Portion of a Shape class hierarchy.
21
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

22
The 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
assumed to be the child 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

See Student.cs GradStudent.cs and Academia.cs

23
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

Christmas

Holiday day;
day = new Holiday();
…
day = new Christmas();

24
References and Inheritance
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;

The widening conversion is the most useful
for implementing polymorphism
25
Polymorphism via Inheritance
A polymorphic reference is one which can refer to
different types of objects at different times
An object reference can refer to one object at one
time, then it can be changed to refer to another object
(related by inheritance) at another time
it is the type of the object being referenced, not the
reference type, that determines which method is invoked
polymorphic references are therefore resolved at run-time,
not during compilation; this is called dynamic binding

Careful use of polymorphic references can lead to
elegant, robust software designs

26
Polymorphism via Inheritance
Suppose the Holiday class has a method
called Celebrate, and the Christmas class
redfines 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
27

Contenu connexe

Tendances

A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
M Hussnain Ali
 

Tendances (20)

DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Data types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in javaData types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in java
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Structures
StructuresStructures
Structures
 
OOP
OOPOOP
OOP
 
OOP C++
OOP C++OOP C++
OOP C++
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Structures
StructuresStructures
Structures
 
Structure in c
Structure in cStructure in c
Structure in c
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 

En vedette

c#.Net Windows application
c#.Net Windows application c#.Net Windows application
c#.Net Windows application
veera
 

En vedette (20)

Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5
 
Windows Forms For Beginners Part - 3
Windows Forms For Beginners Part - 3Windows Forms For Beginners Part - 3
Windows Forms For Beginners Part - 3
 
Windows Forms For Beginners Part 5
Windows Forms For Beginners Part 5Windows Forms For Beginners Part 5
Windows Forms For Beginners Part 5
 
Getting Started With Android Application Development [IndicThreads Mobile Ap...
Getting Started With Android Application Development  [IndicThreads Mobile Ap...Getting Started With Android Application Development  [IndicThreads Mobile Ap...
Getting Started With Android Application Development [IndicThreads Mobile Ap...
 
Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4
 
Windows Forms For Beginners Part - 1
Windows Forms For Beginners Part - 1Windows Forms For Beginners Part - 1
Windows Forms For Beginners Part - 1
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 
Windows Forms For Beginners Part - 2
Windows Forms For Beginners Part - 2Windows Forms For Beginners Part - 2
Windows Forms For Beginners Part - 2
 
c#.Net Windows application
c#.Net Windows application c#.Net Windows application
c#.Net Windows application
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
Android Application Development Basic
Android Application Development BasicAndroid Application Development Basic
Android Application Development Basic
 
Windowforms controls c#
Windowforms controls c#Windowforms controls c#
Windowforms controls c#
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
 
Introduction to Android Studio
Introduction to Android StudioIntroduction to Android Studio
Introduction to Android Studio
 
Android studio
Android studioAndroid studio
Android studio
 
Introduction to Android and Android Studio
Introduction to Android and Android StudioIntroduction to Android and Android Studio
Introduction to Android and Android Studio
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 
Android ppt
Android pptAndroid ppt
Android ppt
 

Similaire à Visula C# Programming Lecture 7

Similaire à Visula C# Programming Lecture 7 (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.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
06 inheritance
06 inheritance06 inheritance
06 inheritance
 
Learn C# at ASIT
Learn C# at ASITLearn C# at ASIT
Learn C# at ASIT
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdf
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introduction
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Inheritance
InheritanceInheritance
Inheritance
 
Classes2
Classes2Classes2
Classes2
 
Inheritance
InheritanceInheritance
Inheritance
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
 

Dernier

Dernier (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 

Visula C# Programming Lecture 7

  • 2. Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class, or subclass, or derived class. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class 2
  • 3. Inheritance Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal # weight : int Animal Bird + GetWeight() : int Bird Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent + Fly() : void 3
  • 4. 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 Fig. 9.1 Inheritance examples. 4
  • 5. Declaring a Derived Class Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents } Base class: the “parent” class; if omitted the parent is Object See Book.cs, Dictionary.cs, BookInheritance.cs 5
  • 6. 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 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
  • 7. 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  The details of each modifier are linked on the schedule page Book Example Book.cs Dictionary.cs BookInheritance.cs + public - private # protected # pages : int + GetNumberOfPages() : void Dictionary - definition : int + PrintDefinitionMessage() : void 7
  • 8. Book.cs using System; namespace BookInheritance { /// <summary> /// Summary description for Book. /// </summary> public class Book { protected int pages; //---------------------------------------------------------------// Constructors //---------------------------------------------------------------- public Book() { pages = 1500; } public Book( int pages ) { this.pages = pages; } //---------------------------------------------------------------// Get the number of pages of this book. //---------------------------------------------------------------- public int GetNumberOfPages () { return pages; } public void PrintNumberOfPages () { Console.WriteLine ("Number of pages is: " + pages); } } // end of class Book } // end of namespace 8
  • 9. Dictionary.cs using System; namespace BookInheritance { /// <summary> /// Summary description for Dictionary. /// </summary> public class Dictionary : Book { private int definitions; // number of definitions public Dictionary() { definitions = 52500; } public Dictionary(int definitions) { this.definitions = definitions; } //----------------------------------------------------------------// Prints a message using both local and inherited values. //----------------------------------------------------------------public void PrintDefinitionMessage () { Console.WriteLine ( "Number of definitions: " + definitions ); Console.WriteLine ( "Average definitions per page: " + definitions / pages ); } // end of PrintDefinitionMessages } // end of class Dictionary } // end of namespace 9
  • 10. Book.cs using System; namespace BookInheritance{ class BookInheritance { //----------------------------------------------------------------// Instantiates a derived class and invokes its inherited and // local methods. //----------------------------------------------------------------public static void Main (String[] args) { Dictionary webster = new Dictionary (); int pages = webster.GetNumberOfPages(); // Console.WriteLine( webster.pages ); Console.WriteLine( "Number of pages is " + pages ); webster.PrintDefinitionMessage(); } } // end of class BookInheritance } // end of namespace 10
  • 11. Calling Parent’s Constructor in a Child’s Constructor: the base Reference Constructors are not inherited, even though they have public visibility The first thing a derived class does is to call its base class’ constructor, either explicitly or implicitly implicitly it is the default constructor yet we often want to use a specific constructor of the parent to set up the "parent's part" of the object Syntax: use base public DerivedClass : BaseClass { public DerivedClass(…) : base(…) { // … } } 11
  • 12. Defining Methods in the Child 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 different code in the body The type of the object executing the method determines which version of the method is invoked 12
  • 13. Overriding Methods: Syntax override keyword is needed if a derivedclass method overrides a base-class method If a base class method is going to be overridden it should be declared virtual Example Thought.cs Advice.cs ThoughtAndAdvice.cs 13
  • 14. Thought.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3 { class Thought { //---------------------------------------------------// Prints a message. //---------------------------------------------------public virtual void Message() { Console.WriteLine("I feel like I'm in space "); Console.WriteLine(); } // end of message } } 14
  • 15. Advice.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3 { class Advice:Thought { //--------------------------------------------------------------// Prints a message. This method overrides the parent's version. // It also invokes the parent's version explicitly using super. //----------------------------------------------------------------public override void Message() { Console.WriteLine("Yor are on earth"); Console.WriteLine(); base.Message(); } // end of message } } 15
  • 16. ThoughtandAdvice.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3{ class Program { //----------------------------------------------------------------// Instatiates two objects a invokes the message method in each. //----------------------------------------------------------------static void Main( string[] args ) { Thought t = new Thought(); Advice a = new Advice(); Console.WriteLine( "parked speak: "); t.Message(); Console.WriteLine( "dates speak: "); a.Message(); Console.ReadLine(); }}} 16
  • 17. Overloading vs. Overriding Overloading deals with multiple methods in the same class with the same name but different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different data Overriding lets you define a similar operation in different ways for different object types 17
  • 18. Single vs. Multiple 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 collisions, such as the same variable name in two parents, are hard to resolve Thus, C# and Java support single inheritance, meaning that a derived class can have only one parent class 18
  • 19. Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Animal Reptile Snake Lizard Bird Parrot Mammal Horse Bat 19
  • 20. Another Example: Base Classes and Derived Classes CommunityMemeber Employee Faculty Professor Fig. 9.2 Student Staff Under Alumnus Graduate Instructor Inheritance hierarchy for university CommunityMember. 20
  • 21. Yet Another Example Shape TwoDimensionalShape Circle Fig. 9.3 Square Triangle ThreeDimensionalShape Sphere Cube Cylinder Portion of a Shape class hierarchy. 21
  • 22. 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 22
  • 23. The 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 assumed to be the child 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 See Student.cs GradStudent.cs and Academia.cs 23
  • 24. 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 Christmas Holiday day; day = new Holiday(); … day = new Christmas(); 24
  • 25. References and Inheritance 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; The widening conversion is the most useful for implementing polymorphism 25
  • 26. Polymorphism via Inheritance A polymorphic reference is one which can refer to different types of objects at different times An object reference can refer to one object at one time, then it can be changed to refer to another object (related by inheritance) at another time it is the type of the object being referenced, not the reference type, that determines which method is invoked polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding Careful use of polymorphic references can lead to elegant, robust software designs 26
  • 27. Polymorphism via Inheritance Suppose the Holiday class has a method called Celebrate, and the Christmas class redfines 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 27