0% found this document useful (0 votes)
5 views26 pages

P10ch10 F24

Uploaded by

sim241991
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views26 pages

P10ch10 F24

Uploaded by

sim241991
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

COIS1020H: Programming for

Computer Science

Chapter 10
Introduction to Inheritance

Understanding Inheritance

• Inheritance
– The principle that you can apply knowledge of a
general category to more specific objects
• Advantages of inheritance
– Saves time
– Reduces the chance of errors
– Makes it easier to understand the inherited class
– Makes programs easier to write

1
Understanding Inheritance
Terminology
• Base class
– A class that is used as a basis for inheritance
– Also known as the superclass or parent class
• Derived class or extended class
– A class that inherits from a base class
– A derived class always “is a” case or instance of the
more general base class
– Also known as subclass or child class

Understanding Inheritance
Terminology (cont'd.)
• Ancestors
– List of parent classes from which child class is derived

• Inheritance is transitive
– Child inherits all the members of all its ancestors

2
Extending Classes

• Use a single colon


– Between the derived class name and its base class
name

• Inheritance works only in one direction


– A child inherits from a parent

Employee Base Class


public class Employee
{
private int empNum;
private double empSal;
public int EmpNum set
{ {
get empSal = value;
{ }
return empNum; }
} public string GetGreeting()
set {
{ string greeting = "Hello. I am employee # " + EmpNum;
empNum = value; return greeting;
} }
} }
public double EmpSal
{
get
{
return empSal;
}

3
Extending Classes (cont'd.)
public class CommissionEmployee : Employee
{
private double commissionRate;
public double CommissionRate
{
get
{
return commissionRate;
}
set
{
commissionRate = value;
}
}
}

Extending Classes (cont'd.)


Hello. I am employee # 123
Clerk #123 salary: $30,000.00 per year
public static class DemoEmployees
{
public static void Main()
Hello. I am employee # 234
{ Salesperson #234 salary: $20,000.00 per year
Employee clerk = new Employee(); ...plus 7.00 % commission on all sales
CommissionEmployee salesperson = new CommissionEmployee();
Console.Clear();
clerk.EmpNum = 123;
clerk.EmpSal = 30000.00;
salesperson.EmpNum = 234;
salesperson.EmpSal = 20000;
salesperson.CommissionRate = 0.07;
Console.WriteLine("\n" + clerk.GetGreeting());
Console.WriteLine("Clerk #{0} salary: {1:C} per year", clerk.EmpNum, clerk.EmpSal);
Console.WriteLine("\n" + salesperson.GetGreeting());
Console.WriteLine("Salesperson #{0} salary: {1:C} per year", salesperson.EmpNum, salesperson.EmpSal);
Console.WriteLine("...plus {0:P} commission on all sales", salesperson.CommissionRate);
}
}

4
Using the protected Access
Specifier
• Any derived class inherits all the data and methods of its
base class
– Including private data and methods
– Cannot use or modify private data and methods directly
• A protected data field or method
– Can be used within its own class or in any classes
extended from that class
– Cannot be used by “outside” classes
• Only used within the “family”
• protected methods should be used sparingly
9

Employee Base Class V2


public class Employee
{
private const double MINIMUM = 15000;
private int empNum;
protected double empSal; set
public int EmpNum {
{ if (value < MINIMUM)
get empSal = MINIMUM;
{ else
return empNum; empSal = value;
} }
set }
{ public string GetGreeting()
empNum = value; {
} string greeting = "Hello. I am employee #" + EmpNum;
} return greeting;
public double EmpSal }
{ }
get
{
return empSal;
}

10

10

5
Commission Employee Class V2
public class CommissionEmployee : Employee
{
private double commissionRate;
public double CommissionRate
{
get
{
return commissionRate;
}
set
{
commissionRate = value;
empSal = 0;
}
}
}

11

11

Using the protected Access


Specifier (cont'd.)
public static class DemoSalesperson
{ Salesperson #345 makes $0.00 per year
public static void Main() . . .plus 7.00 % commission on all sales
{
CommissionEmployee salesperson = new CommissionEmployee();
Console.Clear();
salesperson.EmpNum = 345;
salesperson.EmpSal = 20000; sets empSal to 0
salesperson.CommissionRate = 0.07;
Console.WriteLine("Salesperson #{0} makes {1:C} per year", salesperson.EmpNum,
salesperson.EmpSal);
Console.WriteLine(". . .plus {0:P} commission on all sales", salesperson.CommissionRate);
}
}

12

12

6
Overriding Base Class Methods

• Derived class contains data and methods defined in


the original class
• Polymorphism
– Using the same method or property name to indicate
different implementations
– Eg. Although both are vehicles and have an Operate()
method, a bicycle is operated differently than a truck.
• Derived class can override and “hide” methods and
data from the base class

13

13

Virtual Methods/Properties
public class Student set
{ {
private const double RATE = 55.75; credits = value;
private string name; tuition = credits * RATE;
protected int credits; }
protected double tuition; }
public string Name public double Tuition
{ {
get get
{ {
return name; return tuition;
} }
set }
{ }
name = value;
} A virtual property or method
}
public virtual int Credits is one that can be overridden by a
{ property or method with the same
get
{ signature in a child class
return credits;
}

14

14

7
Overriding Base Class Methods
(cont'd.)
public class ScholarshipStudent : Student
{
public override int Credits
{
set The override modifier overrides
{ and “hides” its counterpart in the
credits = value;
tuition = 0; parent class.
}
}
}

15

15

Overriding Base Class Methods


(cont'd.)
public static class DemoStudents
{
Megan's tuition is $836.25
public static void Main()
{
Luke's tuition is $0.00
Student payingStudent = new Student();
ScholarshipStudent freeStudent = new ScholarshipStudent();
Console.Clear();
payingStudent.Name = "Megan";
payingStudent.Credits = 15;
freeStudent.Name = "Luke";
freeStudent.Credits = 15;
Console.WriteLine("{0}'s tuition is {1:C}", payingStudent.Name, payingStudent.Tuition);
Console.WriteLine("{0}'s tuition is {1:C}", freeStudent.Name, freeStudent.Tuition);
}
}

16

16

8
More Polymorphism (Parent Class)
public class Student public virtual int Credits
{
{
get
private const double RATE = 55.75;
{
private string? name;
return credits;
protected int credits; }
protected double tuition; set
public string? Name {
{ credits = value;
get tuition = credits * RATE;
{ }
return name; }
} public double Tuition
set {
{ get
name = value; {
} return tuition;
} }
}
}

17

17

More Polymorphism (Child Classes)


public class ScholarshipStudent : Student public class InternationalStudent : Student
{ {
private int amount; private const double RATE = 155.75;
public int Amount private string? country;
{ public string? Country
get { return amount; } {
set { amount = value; } get { return country; }
} set { country = value; }
public override int Credits }
{ public override int Credits
set {
{ set
credits = value; {
tuition = 0; credits = value;
} tuition = value * RATE;
} }
} }
}

18

18

9
More Polymorphism (GrandChild
Class)
public class GraduateStudent : InternationalStudent
{
private string uDegree;
public string UDegree
{
get { return uDegree; }
set { uDegree = value; }
}
public override int Credits
{
set
{
credits = value;
tuition = 12000;
}
}
}

19

19

More Polymorphism (Driver)


public static class DemoStudents
{
public static void Main()
{
Student pStudent = new Student();
ScholarshipStudent sStudent = new ScholarshipStudent();
InternationalStudent iStudent = new InternationalStudent();
GraduateStudent gStudent = new GraduateStudent();
Console.Clear();
pStudent.Name = "Megan";
pStudent.Credits = 15;
sStudent.Name = "Luke";
sStudent.Credits = 15;
sStudent.Amount = 10000;
iStudent.Name = "Rich";
iStudent.Credits = 15;
iStudent.Country = "Barbados";
gStudent.Name = "Mary";
gStudent.Credits = 25;
gStudent.Country = "Ireland";
gStudent.UDegree = "BSc Computer Science";

20

20

10
More Polymorphism (Driver)
Console.WriteLine("{0}’s tuition is {1:C}", pStudent.Name, pStudent.Tuition);
Console.WriteLine("{0}’s tuition is {1:C}", sStudent.Name, sStudent.Tuition);
Console.WriteLine("The scholarship amount is {0:C}", sStudent.Amount);
Console.WriteLine("{0}’s tuition is {1:C}", iStudent.Name, iStudent.Tuition);
Console.WriteLine("Is a citizen of {0}", iStudent.Country);
Console.WriteLine("{0}’s tuition is {1:C}", gStudent.Name, gStudent.Tuition);
Console.WriteLine("Is a citizen of {0}", gStudent.Country);
Console.WriteLine("And has an undergraduate degree: {0}", gStudent.UDegree);
}
}

Megan's tuition is $836.25


Luke's tuition is $0.00
The scholarship amount is $10,000.00
Rich's tuition is $2,336.25
Is a citizen of Barbados
Mary's tuition is $12,000.00
Is a citizen of Ireland
And has an undergraduate degree: BSc Computer Science

21

21

Accessing Base Class Methods


from a Derived Class
• Use the keyword base to access the parent class method
public class CommissionEmployee : Employee
{
private double commissionRate;
public double CommissionRate
{
get The base keyword allows a child
{
return commissionRate; to access its parent’s methods
}
set
{
commissionRate = value;
empSal = 0;
}
}
new public string GetGreeting()
{
string greeting = base.GetGreeting();
greeting += "\nI work on commission.";
return greeting;
}
} 22

22

11
Employee Base Class
public class Employee
{
private const double MINIMUM = 15000;
private int empNum;
protected double empSal; set
public int EmpNum {
{ if (value < MINIMUM)
get
{ empSal = MINIMUM;
return empNum; else
} empSal = value;
set }
{ }
empNum = value; public string GetGreeting()
}
} {
public double EmpSal string greeting = "Hello. I am employee #" + EmpNum;
{ return greeting;
get }
{ }
return empSal;
}

23

23

Accessing Base Class Methods


from a Derived Class (cont'd.)
public static class DemoSalesperson2
{
public static void Main()
{
CommissionEmployee salesperson = new CommissionEmployee();
Console.Clear();
salesperson.EmpNum = 345;
Console.WriteLine(salesperson.GetGreeting());
}
}
Hello. I am employee # 345
I work on commission.

24

24

12
Understanding How a Derived Class
Object “is an” Instance of the Base Class

• Every derived class object “is a” specific instance of


both the derived class and the base class
• You can assign a derived class object to an object of
any of its superclass types
– C# makes an implicit conversion from derived class
to base class

25

25

Understanding How a Derived Class Object


“is an” Instance of the Base Class (cont'd.)
public static class DemoSalesperson3
{ The first call passes an Employee
public static void Main()
object but the second call passes a
{
CommissionEmployee object
CommissionEmployee salesperson = new CommissionEmployee();
Employee clerk = new Employee();
Console.Clear();
clerk.EmpNum = 234;
salesperson.EmpNum = 345;
DisplayGreeting(clerk); Hi there from #234
DisplayGreeting(salesperson); Hello. I am employee # 234
}
Hi there from #345
public static void DisplayGreeting(Employee emp)
{
Hello. I am employee # 345
Console.WriteLine("Hi there from Employee {0}", emp.EmpNum);
Console.WriteLine(emp.GetGreeting());
}
}

26

26

13
Using the Object Class

• object (or Object) class type in the System


namespace
– Ultimate base class for all other types
– The keyword object is an alias for the
System.Object class

27

27

Using the Object Class (cont'd.)


public static class DiverseObjects Using Student: Method successfully called
{ Using Scholarship Student: Method successfully called
public static void Main()
Using Employee: Method successfully called
{
Student payingStudent = new Student();
ScholarshipStudent freeStudent = new ScholarshipStudent();
Employee clerk = new Employee();
Console.Clear();
Console.Write("Using Student: ");
DisplayObjectMessage(payingStudent);
Console.Write("UsingScholarshlpStudent: ");
DisplayObjectMessage(freeStudent);
Console.Write("Using Employee: ");
DisplayObjectMessage(clerk);
}
public static void DisplayObjectMessage(Object o)
{
Console.WriteLine("Method successfully called");
}
}

28

28

14
Using the Object Class (cont'd.)

29

29

Using the Object Class’s


GetType() Method
• GetType() method
– Returns an object’s type, or class
• Example
Employee someWorker = new Employee();
Console.WriteLine(someWorker.GetType());
Would output Employee

Student csStudent = new Student();


Console.WriteLine(csStudent.GetType());
Would output Student

30

30

15
Using the Object Class’s
ToString() Method
• ToString() method
– Returns a string that holds the class name
• Just as GetType() does
• You should override this method in your own class to
make it more meaningful (Employee: 1234 Hurley)

31

31

Working with Base Class Constructors


• Instantiating an object of a derived class
– Calls the constructor for both the base class and the
derived class
• The base class constructor must execute first
public class Employee
{
private int empNum;
protected double empSal;
public Employee()
{
Console.WriteLine("Employee constructed");
}
}
public class CommissionEmployee : Employee
{
private double commissionRate;
public CommissionEmployee()
{
Console.WriteLine("CommissionEmployee constructed");
}
}
32

32

16
Working with Base Class Constructors
(cont'd.)
public static class DemoSalesperson4
{
public static void Main()
{
Console.Clear();
CommissionEmployee salesperson = new CommissionEmployee();
}
}

Employee constructed
ComissionEmployee constructed

33

33

Using Base Class Constructors that


Require Arguments
• When a base class constructor requires arguments:
– Include a constructor for each derived class you create
• The derived class constructor can contain any
number of statements
– Within the header, provide values for any arguments
required by the base class constructor
• Using the keyword base
• Example
- Assume you have a base class Employee constructor that takes
two parameters (int, string)
public Employee (int eNum, string eName) { code }

34

34

17
Using Base Class Constructors that
Require Arguments (cont’d)
• Examples:
public CommissionEmployee() : base(1234, “XXXX”)
{ Other statements go here }
- CommissionEmployee constructor requires no arguments but the base class
Employee constructor requires 2

public CommissionEmployee(int id, string name) : base(id, name)


{ Other statements go here }
- CommissionEmployee constructor requires 2 arguments and it passes these
on to the base class Employee constructor

public CommissionEmployee(int id, string name, double rate) :


base(id, name)
{ CommissionRate = rate; Other statements go here }
- CommissionEmployee constructor requires 3 arguments, passes 2 to the base
class Employee constructor and uses the other for itself

35

35

Creating and Using Abstract Classes


• Up to this point, a child class inherits all the fields, properties and
methods from its parent class and objects can be created from
both parent and child classes

• Abstract class
– One from which you cannot create concrete objects
• But from which you can inherit
– Use keyword abstract when you declare an abstract class
– Usually contains abstract methods (or properties), although
methods (or properties) are not required
• Abstract method (or property)
– Has no method / property statements
– Derived classes must override it using the keyword override

36

36

18
Creating and Using Abstract
Classes (cont'd.)
public abstract class Animal
{
private string name;
public Animal(string valName)
{
name = valName;
}
public string Name
{
get
{
return name;
}
}
public abstract string Speak();
}

37

37

Creating and Using Abstract


Classes (cont'd.)
public class Dog : Animal
{
public Dog(string name) : base(name)
{
}
public override string Speak()
{
return "woof";
}
}

public class Cat : Animal


{
public Cat(string name) : base(name)
{
}
public override string Speak()
{
return "meow";
}
}

38

38

19
Creating and Using Abstract
Classes (cont'd.)
public static class DemoAnimals
{
public static void Main()
{
Dog dog1 = new Dog("Spot");
Cat cat1 = new Cat("Puff");
Console.Clear();
Console.WriteLine(dog1.Name + " says " + dog1.Speak());
Console.WriteLine(cat1.Name + " says " + cat1.Speak());
}
}
Spot says woof
Puff says meow

39

39

Another Example with Abstract


(Parent Class)
public abstract class Student public abstract int Credits
{ { set; }
private string? name; public double Tuition
protected int credits; {
protected double tuition; get
public string? Name {
{ return tuition;
get }
{ }
return name; }
}
set
{
name = value;
}
}

40

40

20
Abstract Properties (Child Classes)
public class ScholarshipStudent : Student public class InternationalStudent : Student
{ {
private int amount; private const double RATE = 155.75;
public int Amount private string? country;
{ public string? Country
get { return amount; } {
set { amount = value; } get { return country; }
} set { country = value; }
public override int Credits }
{ public override int Credits
set {
{ set
credits = value; {
tuition = 0; credits = value;
} tuition = value * RATE;
} }
} }
}

41

41

Abstract Properties (Child Classes)


public class DomesticStudent : Student
{
private const double RATE = 55.75;
private string? province;
public string? Province
{
get { return province; }
set { province = value; }
}
public override int Credits
{
set
{
credits = value;
tuition = 0;
}
}
}

42

42

21
Abstract Properties (Driver)
public static class DemoStudents
{
public static void Main()
{ Megan's tuition is $836.25
DomesticStudent dStudent = new DomesticStudent(); Was born in NB
ScholarshipStudent sStudent = new ScholarshipStudent();
InternationalStudent iStudent = new InternationalStudent();
Luke's tuition is $0.00
Console.Clear(); The scholarship amount is $10,000.00
dStudent.Name = "Megan"; Rich's tuition is $2,336.25
dStudent.Credits = 15;
Is a citizen of Barbados
dStudent.Province = "NB";
sStudent.Name = "Luke";
sStudent.Credits = 15;
sStudent.Amount = 10000;
iStudent.Name = "Rich";
iStudent.Credits = 15;
iStudent.Country = "Barbados";
Console.WriteLine("{0}'s tuition is {1:C}", dStudent.Name, dStudent.Tuition);
Console.WriteLine("Was born in {0}", dStudent.Province);
Console.WriteLine("{0}'s tuition is {1:C}", sStudent.Name, sStudent.Tuition);
Console.WriteLine("The scholarship amount is {0:C}", sStudent.Amount);
Console.WriteLine("{0}'s tuition is {1:C}", iStudent.Name, iStudent.Tuition);
Console.WriteLine("Is a citizen of {0}", iStudent.Country);
}
}

43

43

Creating and Using Interfaces

• Multiple inheritance
– The ability to inherit from more than one class
• Multiple inheritance is a difficult concept

• Multiple inheritance is prohibited in C#

44

44

22
Creating and Using Interfaces (cont'd.)
• Interface
– Alternative to multiple inheritance
– A collection of methods that can be used by any class
• As long as the class provides a definition to override the
interface’s abstract definitions
– An interface cannot define any constructors and
neither they can define any instance fields and cannot
contain any static members.
• In an abstract class
– Not all methods need to be abstract
• In an interface
– All methods are abstract
45

45

Creating and Using Interfaces (cont'd.)


public class Employee : IWorkable public abstract class Animal : IWorkable
{ {
private string eName; private string aName;
public Employee(string val) public Animal(string val)
{ {
eName = val; aName = val;
} }
public string EName public string AName
{ {
get get
{ return eName; } { return aName; }
} }
public string Work() public abstract string Work();
{ }
return "I teach my classes";
}
}

All classes which uses IWorkable


must have a Work()method (even
derived classes)
46

46

23
Creating and Using Interfaces (cont'd.)
public class Dog : Animal
{
public Dog(string name) : base(name)
{
}
public override string Work()
{
return "I watch the house";
} All classes which uses IWorkable
}
must have a Work()method (even
public class Cat : Animal derived classes)
{
public Cat(string name) : base(name)
{
}
public override string Work()
{
return "I catch mice";
}
}

47

47

Creating and Using Interfaces (cont'd.)


public static class DemoWorking
{
public static void Main()
{
Dog dog1 = new Dog("Butch");
Cat cat1 = new Cat("Fluffy");
Employee bob = new Employee("Robert");
Console.Clear();
Console.WriteLine(dog1.AName + " says " + dog1.Work());
Console.WriteLine(cat1.AName + " says " + cat1.Work());
Console.WriteLine(bob.EName + " says " + bob.Work());
}
}
Butch says I watch the house
Puff says I catch mice
Robert says I teach my classes

48

48

24
Creating and Using Interfaces (cont'd.)

• You cannot instantiate concrete objects from either


abstract classes or interfaces
• A class can inherit from only one base class
– However, it can implement any number of interfaces
• You create an interface when you want derived
classes to override every method
• Interfaces provide you with another way to exhibit
polymorphic behavior

49

49

Summary
• Inheritance is the principle that you can apply your
knowledge of a general category to more specific
objects
• Inheritance terminology
– Base class
• Also known as superclass or parent class
– Extended or derived class
• Also known as subclass or child class
• Use a single colon between the derived class name
and its base class name
• protected access modifier

50

50

25
Summary (cont'd.)
• Derived classes exhibit polymorphic behavior
• Use the keyword base to access members in the
base class
• Every derived class object “is a” specific instance
of both the derived class and the base class
• Every class derives from System.Object
• Instantiating an object of a subclass calls two
constructors
– Base class constructor
– Derived (extended) class constructor

51

51

Summary (cont'd.)
• Within the header of the derived class constructor:
– You can provide values for any arguments required
by the base class constructor
• An abstract class is one from which you cannot
create concrete objects
– But from which you can inherit
• C# provides an alternative to multiple inheritance,
known as an interface

52

52

26

You might also like