P10ch10 F24
P10ch10 F24
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
3
Extending Classes (cont'd.)
public class CommissionEmployee : Employee
{
private double commissionRate;
public double CommissionRate
{
get
{
return commissionRate;
}
set
{
commissionRate = value;
}
}
}
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
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
12
12
6
Overriding Base Class Methods
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
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
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
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);
}
}
21
21
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
24
24
12
Understanding How a Derived Class
Object “is an” Instance of the Base Class
25
25
26
26
13
Using the Object Class
27
27
28
28
14
Using the Object Class (cont'd.)
29
29
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
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
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
35
35
• 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
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
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
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
• Multiple inheritance
– The ability to inherit from more than one class
• Multiple inheritance is a difficult concept
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
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
48
48
24
Creating and Using Interfaces (cont'd.)
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