Lecture 04: Inheritance
Table of Contents
• Inheritance
• Class Hierarchies
• Inheritance in C#
• Accessing Members of the Base Class
• Reusing Classes
• Type of Class Reuse
2
ANIMAL
Extending Classes
Inheritance
Inheritance
Superclass - Parent class, Base Class
The class giving its members to its child class
Subclass - Child class, Derived class
The class taking members from its base class
Base
Superclass
Derived
Subclass
4
Inheritance – Example
Base class
Person
+Name: string
+Address: string
Derived class Derived class
Employee Student
+Company: string +School: string
5
Class Hierarchies
Class Hierarchies
Inheritance leads to hierarchies of classes and/or interfaces in
an application Base class holds
common
Game characteristics
SinglePlayerGame MultiplePlayers-
Game
Minesweepe Solitaire BoardGame …
r
…
Chess Backgam-
mon 7
Inheritance in C#
In C# inheritance is defined by the : operator
class Person { … }
class Student : Person { … } Person
class Employee : Person { … }
Student Employee
Student : Person
8
Inheritance – Derived Class
Derived classes take all members from base classes
Person
Mother : Person
Reusing Person
Father : Person
Student : Person Employee : Person
Reusing Reusing
Student Online Onsite Contract Civil Employee
9
Using Inherited Members
You can access inherited members as usual
class Person { public void Sleep()
{ … } }
class Student : Person { … }
class Employee : Person { … }
Student student = new Student();
[Link]();
Employee employee = new Em-
ployee();
[Link]();
10
Reusing Constructors
Constructors are not inherited
They can be reused by the child classes
class Student : Person {
private School school;
public Student(string name, School
school)
:base(name) {[Link] = school;}
}
11
Thinking about Inheritance – Extends
Derived class instance contains instance of its base class
Person Employee
(Base Class) (Derived Class)
+Sleep():void +Work():void
Student (Derived Class)
+Study():void
12
Transitive Relation
Inheritance has a transitive relation
class Person { … }
class Student : Person { … }
class CollegeStudent : Student { … }
Person
Student
CollegeStudent
13
Multiple Inheritance
In C# there is no multiple inheritance
Only multiple interfaces can be implemented
Person Student
CollegeStudent
14
Accessing Base Class Members
Access to Base Class Members
Use the base keyword
class Person { … }
class Employee : Person {
public void Fire(string reasons)
{
[Link]($"{[Link]} got fired
because of
{reasons}");
}
}
16
Problem: Single Inheritance
Animal
+Eat():void
Dog dog = new Dog();
[Link]();
[Link]();
Dog
+Bark():void
17
Problem: Multiple Inheritance
Animal
+Eat():void
Puppy puppy = new Puppy();
Dog [Link]();
[Link]();
+Bark():voi
d [Link]();
Puppy
+Weep():voi
d
18
Problem: Hierarchical Inheritance
Dog dog = new Dog();
Animal [Link]();
[Link]();
+Eat():void
Dog Cat Cat cat = new Cat();
+Bark():void +Meow():void [Link]();
[Link]();
19
Reusing Code at Class Level
Reusing Classes
Inheritance and Access Modifiers
Derived classes can access all public and protected
members
Internal members are accessed in the same assembly
Private fields are not inherited in subclasses
class Person {
private string id;
string name;
protected string address;
public void Sleep(); }
21
Shadowing Variables
Derived classes can hide superclass variables
class Person { protected int
weight; }
class Patient : Person {
protected float weight;
Hides int weight
public void Method()
{
double weight = 0.5d;
} Hides float weight
}
22
Shadowing Variables – Access
Use base and this to specify member access
class Patient : Person {
protected float weight; Local variable
public void Method() {
double weight = 0.5d;
[Link] = 0.6f;
Instance member
Base class member [Link] = 1;
}
}
23
Virtual Methods
virtual - defines a method that can be overriden
public class Animal
{
public virtual void Eat() { … }
}
public class Dog : Animal
{
public override void Eat() {}
}
24
Sealed Modifier
The sealed modifier prevents other classes from inheriting
from it
You can use the sealed modifier on a method or a property
in a base class:
It enables you to allow classes to derive from your class
Prevents the overriding of specific virtual methods and
properties
25
Inheritance Benefits – Extension
We can extend a class that we can't otherwise change
Collections
List
Extends
CustomList
26
Problem: Random List
Create an list that has
All functionality of a List<string>
Method that returns and removes a random element
Collections
List<string>
+RandomElement():string
RandomList
27
Solution: Random List
public class RandomList : List<string> {
private Random rnd; // TODO: Add construc-
tor
public string RemoveRandomElement() {
int index = [Link](0, [Link]);
string str = this[index];
[Link](index);
return str;
}
}
28
Extension, Composition, Delegation
Types of Class Reuse
Extension
Duplicate code is error prone
Reuse classes through extension
Sometimes the only way
Collections
List<string>
CustomList
30
Composition
Using classes to define classes
class Laptop { Laptop
Monitor monitor;
Monitor
Touchpad touchpad;
Keyboard keyboard;
Touchpad
… Reusing
} classes
Keyboard
31
Delegation
class Laptop
{
Monitor monitor;
Laptop
void IncrBrightness()
[Link](); Monitor
void DecrBrightness() increaseBrightness()
[Link](); decreaseBrightness()
}
32
Problem: Stack of Strings
Create a simple StackOfStrings class which inherits the
Stack<string>
StackOfStrings
+IsEmpty(): Boolean
+AddRange(): void
33
Solution: Stack of Strings
public class StackOfStrings : Stack<string> {
public bool IsEmpty() {
return [Link] == 0;
}
public void AddRange(IEnumerable<string> collection)
{
foreach (var element in collection)
[Link](element);
}
}
34
Summary
Inheritance
… is a powerful tool
for…code reuse
Subclass
… inherits members from
Superclass and can override methods
Look for classes with the same role
Look for IS-A and IS-A-SUBSTITUTE
Consider Composition and Delegation
35
Exercises
• Time to practices