SlideShare a Scribd company logo
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

More Related Content

PPT
Visula C# Programming Lecture 6
PPT
Visula C# Programming Lecture 8
PPT
Basic c#
PPTX
C sharp part 001
PPSX
DITEC - Programming with C#.NET
PPT
C++ oop
PDF
LEARN C#
PDF
Object Oriented Programming using C++ Part III
Visula C# Programming Lecture 6
Visula C# Programming Lecture 8
Basic c#
C sharp part 001
DITEC - Programming with C#.NET
C++ oop
LEARN C#
Object Oriented Programming using C++ Part III

What's hot (20)

PPSX
DISE - Windows Based Application Development in C#
PPT
C++ tutorials
PPSX
Data types, Variables, Expressions & Arithmetic Operators in java
PPTX
02 data types in java
PDF
C sharp chap5
PDF
A COMPLETE FILE FOR C++
PPTX
Data types in c++
PDF
C# Summer course - Lecture 3
PPTX
OOPS IN C++
PPTX
Object oriented programming in C++
PPSX
DIWE - Working with MySQL Databases
PDF
C# Summer course - Lecture 4
PPT
PPTX
OOP C++
PPT
02 Primitive data types and variables
PPTX
Structured Languages
PPT
Structures
PPT
Structure in c
PDF
Introduction to c++ ppt
DISE - Windows Based Application Development in C#
C++ tutorials
Data types, Variables, Expressions & Arithmetic Operators in java
02 data types in java
C sharp chap5
A COMPLETE FILE FOR C++
Data types in c++
C# Summer course - Lecture 3
OOPS IN C++
Object oriented programming in C++
DIWE - Working with MySQL Databases
C# Summer course - Lecture 4
OOP C++
02 Primitive data types and variables
Structured Languages
Structures
Structure in c
Introduction to c++ ppt
Ad

Viewers also liked (20)

PPT
Visula C# Programming Lecture 3
PPT
Visula C# Programming Lecture 5
PDF
Windows Forms For Beginners Part - 3
PDF
Windows Forms For Beginners Part 5
PPS
Getting Started With Android Application Development [IndicThreads Mobile Ap...
PDF
Windows Forms For Beginners Part - 4
PDF
Windows Forms For Beginners Part - 1
PPT
Visula C# Programming Lecture 1
PDF
Windows Forms For Beginners Part - 2
PPT
c#.Net Windows application
PPT
Visula C# Programming Lecture 2
PPT
Android Application Development Basic
PPTX
Windowforms controls c#
PPTX
Creating the first app with android studio
PDF
Introduction to Android Studio
PDF
Android studio
PPTX
Introduction to Android and Android Studio
PPTX
Android Application Development
ZIP
Android Application Development
PPTX
Android ppt
Visula C# Programming Lecture 3
Visula C# Programming Lecture 5
Windows Forms For Beginners Part - 3
Windows Forms For Beginners Part 5
Getting Started With Android Application Development [IndicThreads Mobile Ap...
Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 1
Visula C# Programming Lecture 1
Windows Forms For Beginners Part - 2
c#.Net Windows application
Visula C# Programming Lecture 2
Android Application Development Basic
Windowforms controls c#
Creating the first app with android studio
Introduction to Android Studio
Android studio
Introduction to Android and Android Studio
Android Application Development
Android Application Development
Android ppt
Ad

Similar to Visula C# Programming Lecture 7 (20)

PDF
Inheritance
ODP
Ppt of c++ vs c#
PPTX
CSharp_03_Inheritance_introduction_with_examples
PPTX
Inheritance.pptx
DOCX
Ganesh groups
PDF
Inheritance
PPTX
Object Oriented Programming using c++.pptx
PPTX
Inheritance
PDF
Chapter- 3 Inheritance and Polymorphism-1x4.pdf
PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
PPTX
Inheritance
PPTX
Opp concept in c++
PDF
lecture 6.pdf
PPT
Synapseindia dot net development
PPT
06 inheritance
PPT
Learn C# at ASIT
PDF
OOP Assign No.03(AP).pdf
PPTX
C++ programming introduction
PPT
Inheritance (1)
PDF
Inheritance and interface
Inheritance
Ppt of c++ vs c#
CSharp_03_Inheritance_introduction_with_examples
Inheritance.pptx
Ganesh groups
Inheritance
Object Oriented Programming using c++.pptx
Inheritance
Chapter- 3 Inheritance and Polymorphism-1x4.pdf
M251_Meeting 5 (Inheritance and Polymorphism).ppt
Inheritance
Opp concept in c++
lecture 6.pdf
Synapseindia dot net development
06 inheritance
Learn C# at ASIT
OOP Assign No.03(AP).pdf
C++ programming introduction
Inheritance (1)
Inheritance and interface

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
Classroom Observation Tools for Teachers
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
master seminar digital applications in india
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
Cell Types and Its function , kingdom of life
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
RMMM.pdf make it easy to upload and study
Classroom Observation Tools for Teachers
Weekly quiz Compilation Jan -July 25.pdf
Microbial disease of the cardiovascular and lymphatic systems
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
master seminar digital applications in india
Final Presentation General Medicine 03-08-2024.pptx
Paper A Mock Exam 9_ Attempt review.pdf.
Cell Types and Its function , kingdom of life
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
What if we spent less time fighting change, and more time building what’s rig...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Final Presentation General Medicine 03-08-2024.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Microbial diseases, their pathogenesis and prophylaxis
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf

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