Inheritance allows a class to inherit characteristics from a parent class. The child class inherits methods and data from the parent class. Inheritance is shown with arrows pointing from the child class to the parent class. Common examples of inheritance hierarchies include shapes, animals, and accounts. The protected access modifier allows child classes to access protected members of the parent class. Polymorphism through inheritance allows a reference variable to refer to objects of different classes in the inheritance hierarchy.
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
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