Object Oriented Programming - Inheritance
Object Oriented Programming - Inheritance
Object-Oriented
Programming:
Inheritance
Objectives
• To understand inheritance and software reusability.
• To understand the notions of base classes and derived
classes.
• To understand member access modifiers
Protected and Friend.
• To understand MyBase classes and derived classes.
• To understand visual inheritance.
Say not you know another entirely, till you have divided an
inheritance with him.
Johann Kasper Lavater
This method is to define as the number of a class the class of
all classes similar to the given class.
Bertrand Russell
Good as it is to inherit a library, it is better to collect one.
Augustine Birrell
Chapter 9 Object-Oriented Programming: Inheritance 581
Outline
9.1 Introduction
9.2 Base Classes and Derived Classes
9.3 Protected and Friend Members
9.4 Relationship between Base Classes and Derived Classes
9.5 Constructors and Finalizers in Derived Classes
9.6 Implicit Derived-Class-Object to Base-Class-Object Conversion
9.7 Software Engineering with Inheritance
9.8 Composition vs. Inheritance
9.9 Case Study: Point, Circle, Cylinder
9.10 Visual Inheritance
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises
9.1 Introduction
In this chapter and the next, we discuss object-oriented programming (OOP) and one of its
key component technologies—inheritance. Inheritance is a form of software reusability in
which classes are created by absorbing an existing class’s attributes and behaviors and em-
bellishing these with new capabilities. Software reusability saves time in program develop-
ment. It encourages the reuse of proven and debugged high-quality software, reducing
problems after a system becomes operational.
When creating a class, instead of writing completely new instance variables and
instance methods, the programmer can designate that the new class should inherit the
instance variables and methods of another class. The previously defined class is called the
base class, and the new class is referred to as the derived class. Each derived class becomes
a candidate to be a base class for future derived classes. The direct base class is the base
class from which the derived class explicitly inherits (using the Inherits keyword). An
indirect base class is inherited from two or more levels up the class hierarchy.
With single inheritance, a class is derived from one base class. Visual Basic does not
support multiple inheritance (i.e., a class is derived from several base classes) as does C++,
but it does support the notion of interfaces. Interfaces help Visual Basic achieve many of
the advantages of multiple inheritance without the associated problems. In this chapter, we
discuss creating and using interfaces.
A derived class, which normally adds instance variables and methods of its own, is
generally larger than its base class. Therefore, a derived class is more specific than its base
class and represents a smaller group of objects. With single inheritance, the derived class
not only contains the behaviors of its base class, but can also contain additional behaviors.
Every object of a derived class is also an object of that derived class’s base class. How-
ever, the converse is not true—base-class objects are not objects of their derived classes.
We can take advantage of this relationship to perform powerful manipulations. For
example, through inheritance we can link to a list of base-class objects a wide variety of
objects of classes inherited from that base class. This allows a variety of objects to be pro-
582 Object-Oriented Programming: Inheritance Chapter 9
cessed in a general way—as we will see in Chapter 10, this is called polymorphism and is
key to object-oriented programming.
We also introduce new forms of member access control in this chapter—Protected
access and Friend access. Derived-class methods and properties can access Protected
base-class members. Members with Friend access are accessible to objects inside the
current project, but are inaccessible to objects outside the project.
Experience in building software systems indicates that significant portions of the code
deal with closely related special cases. It becomes difficult in such systems to see the “big
picture,” because the programmer often becomes preoccupied with special cases. Object-
oriented programming provides several ways to focus on designing the system in its
entirety—i.e., focusing on the commonality among objects in the system—rather than the
special cases. This process is called abstraction.
If a procedural program contains many closely related special cases, then it is common
to find Select Case structures or nested If/Then/ElseIf structures that distinguish
among the special cases and provide the processing logic to deal with each case individu-
ally. We will show how to use inheritance and polymorphism to replace such Select
Case logic with simpler logic.
We distinguish between the “is-a” relationship and the “has-a” relationship. “Is-a”
represents inheritance. In an “is-a” relationship, an object of a derived class also may be
treated as an object of its base class. “Has-a” stands for composition (as we discussed in
Chapter 8). In a “has-a” relationship, a class object contains one or more object references
as members. For example, a bicycle has a steering wheel and, similarly, a wheel has spokes.
A derived class’s methods may need to access certain of its base class’s instance vari-
ables and methods. A derived class can access the Public and Protected members of
its base class. Base-class members that should not be accessible to a derived class via inher-
itance are declared Private in the base class. A derived class can effect state changes in
Private base-class members only through Public and Protected methods provided
in the base class and inherited into the derived class.
Software Engineering Observation 9.1
A derived class cannot directly access Private members of its base class. 9.1
A problem with inheritance is that a derived class can inherit methods that it does not
need or should not have. It is the class designer’s responsibility to ensure that the capabil-
ities provided by a class are appropriate for future derived classes. Even when the base-
class method is appropriate for a derived class, that derived class often requires the method
to perform a task in a manner specific to the derived class. In such cases, the base-class
method can be overridden (redefined) in the derived class with an appropriate implemen-
tation.
New classes can inherit from abundant class libraries. Organizations develop their own
class libraries and can take advantage of other libraries available worldwide. Someday,
Chapter 9 Object-Oriented Programming: Inheritance 583
the vast majority of new software may be constructed from standardized reusable compo-
nents, as hardware often is constructed today. This will help meet the challenges of devel-
oping more powerful and abundant software.
CStudent CGraduateStudent
CUndergraduateStudent
CShape CCircle
CTriangle
CRectangle
CLoan CCarLoan
CHomeImprovementLoan
CMortgageLoan
CEmployee CFacultyMember
CStaffMember
CAccount CCheckingAccount
CSavingsAccount
Every derived-class object “is an” object of its base class, and one base class can have
many derived classes; therefore, the set of objects represented by a base class is typically
larger than the set of objects represented by any of its derived classes. For example, the
base-class CVehicle represents all vehicles, such as cars, trucks, boats, bicycles, etc.
Derived-class CCar represents only a small subset of all CVehicles.
Inheritance relationships form tree-like hierarchical structures. A class exists in a hier-
archical relationship with its derived classes. A class can exist by itself, but when it is used
with inheritance, a class becomes either a base class, supplying attributes and behaviors to
other classes, or a derived class, inheriting its attributes and behaviors.
Let us develop a simple inheritance hierarchy. A university community has thousands
of members. These members consist of employees, students and alumni. Employees are
either faculty members or staff members. Faculty members are either administrators (such
as deans and department chairpersons) or teachers. This organizational structure yields the
inheritance hierarchy in Fig. 9.2. Note that the inheritance hierarchy could contain many
584 Object-Oriented Programming: Inheritance Chapter 9
other classes. For example, students can be graduate or undergraduate students. Undergrad-
uate students can be freshman, sophomores, juniors and seniors. The arrows in the hier-
archy represent the “is-a” relationship. For example, as we follow the arrows in this class
hierarchy, we can state, “a CEmployee is a CCommunityMember” or “a CTeacher is
a CFaculty member.” CCommunityMember is the direct base class of CEmployee,
CStudent and CAlumni. CCommunityMember is an indirect base class of all the
other classes in the hierarchy diagram.
CCommunityMember
CFaculty CStaff
CAdministrator CTeacher
Class CTwoDimensionalShape
Inherits IShape
With inheritance, Private members of a base class are not directly accessible from
that class’s derived classes, but the Private base-class members are still inherited. All
members of a base class are inherited. All other base-class members become members of
the derived class using their original member access (i.e., Public members of the base
class become Public members of the derived class, and Protected members of the
base class become Protected members of the derived class). Through these inherited
base-class members, the derived class can manipulate Private members of the base class
(if these inherited members provide such functionality in the base class). Although this con-
cept may sound a bit complex, we will soon clarify this with live-code examples.
Chapter 9 Object-Oriented Programming: Inheritance 585
CShape
CTwoDimensionalShape CThreeDimensionalShape
It is possible to treat base-class objects and derived-class objects similarly; their com-
monality is expressed in the attributes and behaviors of the base class. Objects of all classes
derived from a common base class can be treated as objects of that base class. We will con-
sider many examples that take advantage of this relationship with an ease of programming
not available in non-object-oriented languages, such as C.
classes derived from a particular base class are different from one another, we can create
an array of references to these objects, as long as we treat them as base-class objects. How-
ever, the reverse is not true: A base-class object is not an object of any of its derived classes.
Common Programming Error 9.1
Treating a base-class object as a derived-class object can cause errors. 9.1
Our first example of inheritance is shown in Fig. 9.4, Fig. 9.5 and Fig. 9.6. Class
CPoint (Fig. 9.4) represents an x-y coordinate pair. Class CCircle (Fig. 9.5), which
represents a circle, inherits from CPoint—class CCircle “is a” CPoint but also con-
tains a radius. Module modInheritTest (Fig. 9.6), which runs the application with
method Main, demonstrates assigning derived-class references to base-class references
and casting base-class references to derived-class references.
Let us first examine the CPoint (Fig. 9.4) class definition. The Public services of
class CPoint include methods SetPoint and ToString, properties X and Y and two
CPoint constructors. The instance variables xCoordinate and yCoordinate of
CPoint are specified as Protected (line 8). This prevents clients of CPoint objects
from directly accessing the data, but enables classes derived from CPoint to access the
inherited instance variables directly. If the data were specified as Private, clients would
have to use the non-Private methods of CPoint to access the data, even by derived
classes.
9
10 ' default constructor
11 Public Sub New()
12
13 ' implicit call to MyBase Object constructor occurs here
14 SetPoint(0, 0)
15 End Sub
16
17 ' constructor
18 Public Sub New(ByVal xValue As Integer, _
19 ByVal yValue As Integer)
20
21 ' implicit call to MyBase Object constructor occurs here
22 SetPoint(xValue, yValue)
23 End Sub
24
25 ' set x and y coordinates of the point
26 Public Sub SetPoint(ByVal xValue As Integer, _
27 ByVal yValue As Integer)
28
29 X = xValue
30 Y = yValue
31 End Sub
32
33 ' property xCoordinate
34 Public Property X() As Integer
35
36 Get
37 Return xCoordinate
38 End Get
39
40 Set(ByVal value As Integer)
41 xCoordinate = value
42 End Set
43
44 End Property ' X
45
46 ' property for yCoordinate
47 Public Property Y() As Integer
48
49 Get
50 Return yCoordinate
51 End Get
52
53 Set(ByVal value As Integer)
54 yCoordinate = value
55 End Set
56
57 End Property ' Y
58
59 ' convert point to String
60 Public Overrides Function ToString() As String
61 Return "[" & xCoordinate & ", " & yCoordinate & "]"
62 End Function
Fig. 9.4 Class CPoint represents an x-y coordinate pair.
588 Object-Oriented Programming: Inheritance Chapter 9
63
64 End Class ' CPoint
Note that method ToString (lines 60–62) contains the keyword Overrides in its
declaration. Every class in Visual Basic (such as class CPoint) inherits either directly or
indirectly from class System.Object, which is the root of the class hierarchy, and there-
fore inherits the eight methods defined by class Object. One such method is ToString,
which returns a String containing the object’s name and class—this method is used to
convert any class object to a String representation and sometimes is called implicitly by
the program (e.g., when an object is added to a String). (We discuss other methods of
class Object as we encounter them throughout the book.) Method ToString of class
CPoint overrides the original ToString from class Object—when invoked, method
ToString of class CPoint returns a String containing the xCoordinate and yCo-
orindate (line 62), instead of returning the String containing the object’s name and
class. We explain the benefits of this when we discuss how module modInheritance-
Test uses classes CPoint and CCircle.
Software Engineering Observation 9.5
Every class in Visual Basic is a direct or indirect derived class of Object, so programmers
are not required to name Object explicitly as the base class of a user-defined class. The
Visual Basic compiler sets the base class of a derived class to Object when the program
does not specify a base class explicitly. 9.5
We mentioned in Section 9.2 that class constructors are never inherited. Therefore,
Class CPoint does not inherit class Object’s constructor. However, class CPoint’s
constructors (lines 11–23) call class Object’s constructor implicitly. In fact, every
derived-class constructor always calls its direct base-class’s constructor as its first task
either implicitly or explicitly (the syntax for this call is discussed momentarily). If there is
no explicit call to the base-class constructor, Visual Basic calls the base class’s default (no-
argument) constructor—the comments on lines 13 and 21 indicate where the calls to the
base-class Object’s default constructor occur.
Class CCircle (Fig. 9.5) inherits from class CPoint. The Inherits keyword in
the class declaration (line 5) indicates the inheritance. Class CCircle inherits all the (non-
Private) members of class CPoint, except for the constructors. Thus, the Public
interface to CCircle includes the Public methods inherited from class CPoint, the
two overloaded CCircle constructors, the CCircle methods Area and ToString
and the Radius property. Note that method Area (lines 39–41) uses predefined constant
Math.PI from class Math to calculate the area of a circle.
6
7 Protected circleRadius As Double
8
9 ' default constructor
10 Public Sub New()
11
12 ' implicit call to superclass constructor here
13 Radius = 0
14 End Sub
15
16 ' constructor
17 Public Sub New(ByVal radiusValue As Double, _
18 ByVal xValue As Integer, ByVal yValue As Integer)
19
20 ' use MyBase to call superclass constructor explicity
21 MyBase.New(xValue, yValue)
22 Radius = radiusValue
23 End Sub
24
25 ' property for circleRadius
26 Public Property Radius() As Double
27
28 Get
29 Return circleRadius
30 End Get
31
32 Set(ByVal value As Double)
33 circleRadius = value
34 End Set
35
36 End Property ' Radius
37
38 ' calculate CCircle area
39 Public Function Area() As Double
40 Return Math.PI * radius ^ 2
41 End Function
42
43 ' convert CCircle to String
44 Public Overrides Function ToString() As String
45 Return "Center= " & MyBase.ToString & _
46 "; Radius = " & circleRadius
47 End Function
48
49 End Class ' CCircle
The CCircle constructors (lines 10–23) must invoke a CPoint constructor to ini-
tialize the base-class portion (variables xCoordinate and ycoordinate inherited
from class CPoint) of a CCircle object. The default constructor (lines 10–14) does not
call a CPoint constructor explicitly, so VB calls class CPoint’s default constructor
implicitly, which initializes base-class members xCoordinate and yCoordinate to
zeros. If the CPoint class (Fig. 9.4) contained only the constructor in lines 18–23 (i.e., did
not provide a default constructor), a compiler error would occur.
590 Object-Oriented Programming: Inheritance Chapter 9
Lines 17–23 declare the CCircle constructor that invokes the second CPoint con-
structor explicitly using the base-class constructor-call syntax (i.e., keyword MyBase fol-
lowed by a set of parentheses containing the arguments to the base-class constructor) In this
case, the values xValue and yValue are passed to initialize the base-class members
xCoordinate and yCoordinate. The MyBase reference followed by the dot oper-
ator accesses the original base-class version of that method—in this constructor,
MyBase.New invokes the CPoint constructor explicitly (line 21). To call the base-class
default constructor explicitly, the call to a base-class constructor must be the first statement
in the derived-class-constructor definition.
Common Programming Error 9.3
If the arguments to a MyBase call by a derived class to its base-class constructor do not
match the parameters specified in one of the base-class constructor definitions, a syntax er-
ror occurs. 9.3
example, point1 does not refer to a CCircle, so the condition fails (line 40), and lines
41–42 append to output a String that indicates the result.
Common Programming Error 9.4
Trying to cast an object to one of its derived types can cause an InvalidCastExcep-
tion to occur. 9.4
followed by the name and path of the executing program. We discuss how to deal with this
kind of situation in Chapter 11.
If the classes in a class hierarchy define finalizer methods, the derived-class finalizer
should invoke the base-class finalizer (as its last action) to free all object resources before
the garbage collector reclaims the memory for that object.
Creating a finalizer actually overrides an object’s Finalize method. As we dis-
cussed in Chapter 8, method Finalize belongs to class Object and is therefore a
member of all classes. By creating a finalizer for a class, we can specify the execution when
method Finalize is called for an object of this class. The .NET Framework handles gar-
bage collection for the programmer. Although we demonstrate finalizers in this section,
they often are not needed in Visual Basic classes.
Class CPoint2 (Fig. 9.7) contains two constructors, a finalizer, methods ToString
and SetPoint and members xCoordinate and yCoordinate. Class CPoint2 dif-
fers from class CPoint (Fig. 9.4) in two ways. Method Finalize (lines 28–31) is
invoked just before the garbage collector reclaims a CPoint2 object’s memory. The con-
structors and Finalize method use the Me reference in Console.WriteLine (lines
15, 24 and 29) to make implicit calls to method ToString, which displays String rep-
resentations of the CPoint2’s references that invoked the methods.
594 Object-Oriented Programming: Inheritance Chapter 9
52
53 Set(ByVal value As Integer)
54 yCoordinate = value
55 End Set
56
57 End Property ' Y
58
59 ' convert CPoint2 to String
60 Public Overrides Function ToString() As String
61 Return "[" & xCoordinate & ", " & yCoordinate & "]"
62 End Function
63
64 End Class ' CPoint
Class CCircle2 (Fig. 9.5), which inherits from class CPoint, contains two con-
structors, a finalizer (method Finalize), method ToString and Protected instance
variable circleRadius. The constructors and method Finalize display the
CCircle2 references that invoked the methods. Note that method Finalize uses key-
word MyBase to invoke method Finalize of class CPoint (line 48). Also note that the
CCircle’s ToString method (lines 52–55) invokes the CPoint2’s ToString
method via MyBase (line 53).
Good Programming Practice 9.1
The last statement in a Finalize method of a derived class should invoke the base class’s
Finalize method (via keyword MyBase) to free base-class resources. 9.1
calling method ToString implicitly (using the Me reference), then returns program con-
trol to the CCircle2 constructor. The CCircle2 constructor outputs the complete
CCircle2 by calling method ToString. Notice that the first two lines of the output
from this program show values for xCoordinate, yCoordinate and circleRa-
dius. The CCircle’s ToString method will execute, because a CCircle2 object is
being referenced at that point in execution. When the CPoint2 constructor invokes
method ToString, the program displays 0 for the circleRadius value, because the
CCircle2 constructor has not yet initialized the circleRadius. Member cir-
cleRadius obtains a value of 0, because the creation of our CCircle2 object causes
default values to be assigned to the class’s members.
Fig. 9.9 Demonstrate order in which constructors and finalizers are called.
Line 11 then instantiates CCircle2 object circle2. Again, this invokes the
CCircle2 constructor, which invokes the CPoint2 constructor. Notice in the output
window that the body of the CPoint2 constructor is performed before the body of the
CCircle2 constructor. This shows that objects are constructed “inside out” (i.e., the base-
class constructor is called first).
598 Object-Oriented Programming: Inheritance Chapter 9
Line 13 sets circle1 to Nothing, then line 14 sets circle2 to Nothing, indi-
cating that neither of these objects is needed any longer, so Visual Basic marks the memory
occupied by circle1 and circle2 for (eventual) garbage collection. Visual Basic calls
method Finalize before the garbage collector reclaims the space of these objects (note
the last two lines of the output). The garbage collector is a low-priority thread that runs in
the application’s background (threads are explained in detail in Chapter 14). Line 16 calls
System.GC.Collect, which forces the garbage collector to run. Visual Basic does not
guarantee when or how often objects will be garbage collected, so Visual Basic cannot
guarantee which object’s Finalize method will execute first. We use
System.GC.Collect when we want to free memory by eliminating unnecessary
objects. Note that in the command-line output window, both the CCircle2 and
CPoint2 Finalize methods are called when the CCircle2 objects are garbage col-
lected.
example, in a payroll system we need to be able to walk through an array of employees and
calculate the weekly pay for each person. Intuition suggests that using base-class references
would enable the program to call only the base-class payroll calculation routine (if there is
such a routine in the base class). We need a way to invoke the proper payroll calculation
routine for each object, whether it is a base-class object or a derived-class object, and to do
this simply by using the base-class reference. We learn how to create classes that use this
behavior when we consider polymorphism and dynamic binding in Chapter 10.
A base class denotes commonality. All classes derived from a base class inherit the
capabilities of that base class. In the object-oriented design process, the designer looks for
similarity among a set of classes and factors it out to form a base class. Derived classes then
are customized beyond the capabilities inherited from the base class.
Software Engineering Observation 9.11
Just as the designer of non-object-oriented systems should avoid proliferation of functions,
the designer of object-oriented systems should avoid proliferation of classes. Proliferating
classes creates management problems and can hinder software reusability, because it can
become difficult for a potential user to locate the most appropriate class of a huge collection.
The trade-off is to create fewer classes, providing substantial additional functionality, but
such classes might be too rich. 9.11
6 Module modPointTest
7
8 Sub Main()
9 Dim point As CPoint
10 Dim output As String
11
12 point = New CPoint(72, 115) ' instantiate CPoint object
13
14 ' display default point value
15 output = "X coordinate is " & point.X & _
16 vbCrLf & "Y coordinate is " & point.Y
17
18 point.SetPoint(10, 10) ' set new point
19
20 ' display new point value
21 output &= vbCrLf & vbCrLf & _
22 "The new location of point is " & point.ToString()
23
24 MessageBox.show(output, "Demonstrating Class Point")
25 End Sub ' Main
26
27 End Module ' modPointTest
In our next example, we provide class CCircle (Fig. 9.11). This class has only one
difference from class CCircle of Fig. 9.5—method Area (lines 39–42) now has key-
word Overridable in its declaration (line 39). This keyword indicates that subclasses
of class CCircle (e.g., class Cylinder, as we will see momentarily) may override
method Area. With keyword Overridable, we may specify those methods that we
wish a subclass to override—a method that has not been declared Overridable may not
be overridden. Method ToString of class Object is declared Overridable, so sub-
classes CPoint and CCircle can override this method.
Common Programming Error 9.8
A syntax error occurs if a derived class overrides a method (using keyword Overrides)
that has not been declared Overridable. 9.8
602 Object-Oriented Programming: Inheritance Chapter 9
Figure 9.13 shows class CCylinder, which inherits from class CCircle (line 5).
Class CCylinder’s Public interfaces include the inherited CCircle methods, the
inherited CPoint methods, the CCylinder constructor, the property Height and
CCylinder methods Area, Volume and ToString. Note that method Area (lines
45–48) overrides method Area of class CCircle—the overriding was made possible by
declaring method Area of class CCircle as Overridable. Class CCylinder also
overrides method Volume (lines 51–53) of class CPoint, because cylinders have
volume.
Fig. 9.13 Class Cylinder inherits from class CCircle and overrides method
Area.
Figure 9.14 is a modCylinderTest application to test the CCylinder class. Line
11 instantiates an object of class CCylinder. Lines 15–17 use properties X, Y, Radius
and Height to obtain information about the CCylinder object, because modCylin-
derTest cannot reference the Protected data of class CCylinder directly. Lines
20–22 use method SetPoint and properties Height and Radius to reset the CCyl-
inder’s x-y coordinates, height and radius. Lines 25–34 then use properties to obtain
CCylinder’s x-y coordinate, radius, height, area and volume to display to the user.
3
4 Imports System.Windows.Forms
5
6 Module modCylinderTest
7
8 Sub Main()
9
10 ' instantiate object of class CCylinder
11 Dim cylinder As New CCylinder(5.7, 2.5, 12, 23)
12 Dim output As String
13
14 ' properties get initial x-y coordinate, radius and height
15 output = "X coordinate is " & cylinder.X & vbCrLf & _
16 "Y coordinate is " & cylinder.Y & vbCrLf & "Radius is " & _
17 cylinder.Radius & vbCrLf & "Height is " & cylinder.Height
18
19 ' properties set new x-y coordinate, radius and height
20 cylinder.SetPoint(2, 2)
21 cylinder.Height = 10
22 cylinder.Radius = Convert.ToInt32(4.25)
23
24 ' get new x-y coordinate and radius
25 output &= vbCrLf & vbCrLf & "The new location, radius " & _
26 "and height of cylinder are" & vbCrLf & "Center = [" & _
27 cylinder.X & ", " & cylinder.Y & "];" & _
28 " Radius = " & cylinder.Radius & ";"
29
30 ' get new height, area and volume
31 output &= "Height = " & cylinder.Height & _
32 vbCrLf & vbCrLf & "Area is " & _
33 String.Format("{0:F}", cylinder.Area()) & vbCrLf & _
34 "Volume is " & String.Format("{0:F}", cylinder.Volume())
35
36 MessageBox.Show(output, "Demonstrating Class CCylinder")
37 End Sub ' Main
38
39 End Module ' modCylinderTest
Fig. 9.15 Class FrmInheritance, which inherits from class Form, contains a
button (Learn More).
608 Object-Oriented Programming: Inheritance Chapter 9
Fig. 9.15 Class FrmInheritance, which inherits from class Form, contains a
button (Learn More).
SUMMARY
• Software reusability saves time in program development.
• The direct base class of a derived class is the base class from which the derived class explicitly
inherits (via keyword Inherits). An indirect base class of a derived class is two or more levels
up the class hierarchy from that derived class.
• With single inheritance, a class is derived from one base class. VB does not support multiple in-
heritance (as C++ does) but it does support the notion of interfaces. Interfaces help VB achieve
many of the advantages of multiple inheritance without the associated problems.
• A derived class can add instance variables and instance methods of its own, so a derived class is
often larger than its base class.
• A derived class is more specific than its base class and represents a smaller group of objects.
• Every object of a derived class is also an object of that class’s base class. However, the converse
is not true—base-class objects are not objects of that base class’s derived classes.
• Derived-class methods and properties can access Protected base-class members.
• “Is a” is inheritance. In an “is-a” relationship, an object of a derived class may also be treated as
an object of its base class.
• “Has a” is composition. In a “has-a” relationship, a class object has one or more objects of other
classes as members.
• A derived class cannot directly access Private members of its base class.
• A derived class can access the Public, Protected and Friend members of its base class if
it is in the same project as the base class.
• When a base-class member is inappropriate for a derived class, that member can be overridden (re-
defined) in the derived class with an appropriate implementation.
• Inheritance relationships form tree-like hierarchical structures. A class exists in a hierarchical re-
lationship with its derived classes.
• It is possible to treat base-class objects and derived-class objects similarly; that commonality is
expressed in the attributes and behaviors of the base class.
• A base class’s Public members are accessible anywhere the program has a reference to an object
of that base class or to one of its derived classes.
610 Object-Oriented Programming: Inheritance Chapter 9
• A base class’s Private members are accessible only within the definition of that base class.
• A base class’s Protected-access members have an intermediate level of protection between
Public and Private access. A base class’s Protected members may be accessed only in
that base class or in any classes derived from that class.
• A base class’s Friend members may be accessed only by objects in the same project (Friend
members have what is called project access).
• When a derived-class method overrides a base-class method, the base-class method may be ac-
cessed from the derived class by preceding the base-class method name with keyword MyBase
followed by the dot operator (.).
• An object of a derived class can be treated as an object of its base class.
• A base-class object can not be treated as an object of one of its derived classes.
• An explicit cast can be used to convert a base-class reference to a derived-class reference.
• A derived class can redefine a base-class method using the same signature; this is called overriding
that base-class method. When the method is mentioned by name in the derived class, the derived-
class version is called.
• When an object of a derived class is instantiated, the base class’s constructor is called immediately
(either explicitly or implicitly) to do any necessary initialization of the base-class instance vari-
ables in the derived-class object.
• An explicit call to a base-class constructor (via the MyBase reference) can be provided in the de-
rived-class constructor. Otherwise, the derived-class constructor will call the base-class default
constructor (or default constructor) implicitly.
• Base-class constructors are not inherited by derived classes.
• Referring to a base-class object with a derived-class reference is a syntax error.
• We can use inheritance to create Forms to display a GUI—Forms are classes and inherits from
class System.Windows.Forms.Form
• Visual inheritance allows us to create Forms by inheriting from other Forms. A derived class in-
herits all visual aspects from these base classes, such as sizing, component layout, spacing be-
tween GUI components, color, fonts and the like.
TERMINOLOGY
abstraction
attributes (data)
base class
base-class constructor
base-class default constructor
base-class finalizer
base-class object
base-class reference
MyBase reference
behavior
cast operation
class library
composition
constructor
dangerous cast
data abstraction
default constructor
Chapter 9 Object-Oriented Programming: Inheritance 611
derived class
derived-class constructor
derived-class reference
direct base class
dot (.) operator
dynamic binding
extend a class
garbage collector
“has-a” relationship
hierarchy diagram
indirect base class
information hiding
inheritance
Inherits keyword
inheritance hierarchy
inherited instance variable
instance variable
Friend access modifier
Friend member access
InvalidCastException
“is-a” relationship
member-access operator
multiple inheritance
object of a base class
object of a derived class
object-oriented programming (OOP)
OOP (object-oriented programming)
overloaded constructor
overloading
override method ToString
overriding
overriding a base-class method
overriding a method
polymorphism
Private base-class member
project access
Protected access
Protected base-class member
Protected instance variable
Protected internal member access
protected members of a base class
Protected members of a derived class
Public interface
Public members of a derived class
reusable component
single inheritance
software reusability
software reuse
standard reusable component
visual inheritance
612 Object-Oriented Programming: Inheritance Chapter 9
SELF-REVIEW EXERCISES
9.1 Fill in the blanks in each of the following statements:
a) is a form of software reusability in which new classes absorb the attributes
and behaviors of existing classes and embellish these with new capabilities.
b) A base class’s members can only be accessed in that class’s definition or in
derived classes’ definitions.
c) In a(n) relationship, an object of a derived class also may be treated as an
object of its base class.
d) In a(n) relationship, a class object has one or more references to objects of
other classes as members.
e) A class exists in a relationship with its derived classes.
f) A base class’s members are accessible anywhere the program has a refer-
ence to that base class or to one of its derived classes.
g) A base class’s access members serve as an intermediate level of protection
between Public and Private access.
h) A base class’s members may be accessed only in the same project (called
project access).
i) When an object of a derived class is instantiated, the base class’s is called
implicitly of explicitly to do any necessary initialization of the base-class instance vari-
ables in the derived-class object.
j) Derived-class constructors can call base-class constructors via the reference.
9.2 State whether each of the following is true or false. If false, explain why.
a) It is possible to treat base-class objects and derived-class objects similarly.
b) Base-class constructors are not inherited by derived classes.
c) The derived-class finalizer should invoke the base-class finalizer (as its last action) to
free all object resources.
d) Derived-class objects cannot be treated as base-class objects.
e) Referring to a derived-class object with a base-class reference generate a syntax error.
f) A has-a relationship is implemented by inheritance.
g) All methods, by default, may be overridden.
h) A Car class has an A good example of an “is a” relationship with its SteeringWheel
and Brakes objects.
i) Inheritance encourages the reuse of proven and debugged high-quality software.
j) In visual inheritance, when a derived class inherits all visual aspects from these base
classes, such as sizing, component layout, spacing between GUI components, and colors.
EXERCISES
9.3 Many programs written with inheritance could be solved with composition instead, and vice
versa. Rewrite the program in Fig. 9.10 (and the supporting classes) to use composition rather than
inheritance. After you do this, assess the relative merits of the two approaches for both the Point,
Circle, Cylinder problem and object-oriented programs in general.
9.4 Explain why each of the variables string1, string2 and string3 are considered in-
accessible (and will thus generate a syntax error) in the following program. Assume that Class1 and
Class2 are in different projects, but that the reference to Class1 has been declared.
Class Class1
Class Class2
Inherits Class1
9.5 Rewrite the CPoint, CCircle, CCylinder program in Fig. 9.10 as a CPoint,
CSquare, CCube program. Do this two ways—once with inheritance and once with composition.