Download presentation
Presentation is loading. Please wait.
Published byJulia Stone Modified over 6 years ago
1
Object-Oriented Programming: Inheritance and Polymorphism
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
2
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
3
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
4
10.1 Introduction This chapter continues our discussion of object-oriented programming by introducing inheritance-, a form of software reuse in which a new class is created quickly and easily by absorbing an existing class’s members and customizing them with new or modified capabilities. With inheritance, you can save time during program development and build better software by reusing proven, high-quality classes. Enormous numbers of these classes are available in class libraries provided by Microsoft and independent software vendors. © by Pearson Education, Inc. All Rights Reserved.
5
10.1 Introduction When creating a class, rather than declaring completely new members, you can designate that the new class inherits the members of an existing class. The existing class is called the base class, and the new class is the derived class. A derived class can add its own instance variables, Shared variables, properties and methods, and it can customize methods and properties it inherits. © by Pearson Education, Inc. All Rights Reserved.
6
10.1 Introduction Therefore, a derived class is more specific than its base class and represents a more specialized group of objects. We explain and demonstrate polymorphism, which enables you to conveniently program “in the general” rather than “in the specific.” As we send method calls in this general way, the specific objects “do the right thing.” You’ll see that polymorphism simplifies programming with classes and makes it easy to extend systems with new capabilities. © by Pearson Education, Inc. All Rights Reserved.
7
10.2 Base Classes and Derived Classes
Inheritance enables an is-a relationship. In an is-a relationship, an object of a derived class also can be treated as an object of its base class. For example, a car is a vehicle. Figure 10.1 lists several simple examples of base classes and derived classes—base classes tend to be more general and derived classes tend to be more specific. Base-class objects cannot be treated as objects of their derived classes—although all cars are vehicles, not all vehicles are cars (the other vehicles could be trucks, planes or bicycles, for example) © by Pearson Education, Inc. All Rights Reserved.
8
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
9
10.2 Base Classes and Derived Classes
Because every derived-class object is an object of its base class, and one base class can have many derived classes, 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 Vehicle represents all vehicles, including cars, trucks, boats, bicycles and so on. By contrast, derived class Car represents a smaller, more specific subset of vehicles. © by Pearson Education, Inc. All Rights Reserved.
10
10.2 Base Classes and Derived Classes
CommunityMember Inheritance Hierarchy Figure 10.2 shows a sample UML class diagram of an inheritance hierarchy. A college community has thousands of community members, including 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. The hierarchy could contain many other classes. For example, students can be graduate or undergraduate students. Undergraduate students can be freshmen, sophomores, juniors or seniors. © by Pearson Education, Inc. All Rights Reserved.
11
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
12
10.2 Base Classes and Derived Classes
Each arrow in the inheritance hierarchy represents an is-a relationship. As we follow the arrows upward in this class hierarchy, we can state, for instance, that “an Employee is a CommunityMember” and “a Teacher is a Faculty member.” A direct base class is the class from which a derived class explicitly inherits. An indirect base class is inherited from two or more levels up in the class hierarchy. © by Pearson Education, Inc. All Rights Reserved.
13
10.2 Base Classes and Derived Classes
So, class CommunityMember is the direct base class of Employee, Student and Alumnus, and is an indirect base class of all the other classes in the diagram. Starting from the bottom of the diagram, you can follow the arrows and apply the is-a relationship up to the topmost base class. For example, an Administrator is a Faculty member, is an Employee and is a CommunityMember. © by Pearson Education, Inc. All Rights Reserved.
14
10.2 Base Classes and Derived Classes
Shape Inheritance Hierarchy Now consider the Shape inheritance hierarchy in Fig. 10.3. It begins with base class Shape, which is inherited by derived classes TwoDimensionalShape and ThreeDimensionalShape—Shapes are either TwoDimensionalShapes or ThreeDimensionalShapes. The third level of the hierarchy contains more specific types of Two-DimensionalShapes and ThreeDimensionalShapes. © by Pearson Education, Inc. All Rights Reserved.
15
10.2 Base Classes and Derived Classes
As in Fig. 10.2, we can follow the arrows from the derived classes at the bottom of the diagram to the topmost base class in this class hierarchy to identify several is-a relationships. For example, a Triangle is a TwoDimensionalShape and is a Shape, while a Sphere is a ThreeDimensionalShape and is a Shape. Shape is a direct base class of classes TwoDimensionalShape and ThreeDimensionalShape, and is an indirect base class of all the classes on the third level. © by Pearson Education, Inc. All Rights Reserved.
16
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
17
10.3 Business Case Study: Commission Employees Class Hierarchy
In this section, we use a business-oriented inheritance hierarchy containing types of employees in a company’s payroll application to discuss the relationship between a base class and its derived class. All employees of the company have a lot in common, but Commission employees (who will be represented as objects of a base class) are paid a percentage of their sales, while base-salaried commission employees (who will be represented as objects of a derived class) receive a percentage of their sales plus a base salary. © by Pearson Education, Inc. All Rights Reserved.
18
10.3 Business Case Study: Commission Employees Class Hierarchy
First, we present base class CommissionEmployee. Next, we create a derived class BasePlusCommissionEmployee that inherits from class CommissionEmployee. Then we present an application that creates a BasePlusCommissionEmployee object and demonstrates that it has all the capabilities of the base class and the derived class, but calculates its earnings differently. © by Pearson Education, Inc. All Rights Reserved.
19
10.3.1 Creating Base Class CommissionEmployee
Consider class CommissionEmployee (Fig. 10.4). The Public services of class CommissionEmployee include: a constructor (lines 11–20) properties FirstName (line 4), LastName (line 5), SocialSecurityNumber (line 6), GrossSales (lines 23–36) and CommissionRate (lines 39–52) methods CalculateEarnings (lines 55–57) and ToString (lines 60–66). The class also declares Private instance variables grossSalesValue and commissionRate-Value (lines 7–8) to represent the employee’s gross sales and commission rate. © by Pearson Education, Inc. All Rights Reserved.
20
10.3.1 Creating Base Class CommissionEmployee
Recall that the compiler automatically generates a Private instance variable for each auto-implemented property, so a CommissionEmployee actually has five Private instance variables. The Set accessors of properties GrossSales and CommissionRate validate their arguments before assigning the values to instance variables grossSalesValue and commissionRateValue, respectively. © by Pearson Education, Inc. All Rights Reserved.
21
10.3.1 Creating Base Class CommissionEmployee
Properties FirstName, LastName and SocialSecurityNumber are auto-implemented in this example, because we’re not providing any validation code in their Set accessors. We could validate the first and last names—perhaps by ensuring that they’re of a reasonable length. The social security number could be validated to ensure that it contains nine digits, with or without dashes (for example, or ). © by Pearson Education, Inc. All Rights Reserved.
22
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
23
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
24
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
25
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
26
10.3.1 Creating Base Class CommissionEmployee
All Classes Inherit Directly or Indirectly from Object (from namespace System) You use inheritance to create new classes from existing classes. In fact, every class except Object inherits from an existing class. When you do not explicitly specify the base class in a new class declaration, the compiler implicitly assumes that the class Inherits from Object. The class hierarchy begins with class Object (in namespace System), which every class directly or indirectly extends (or “inherits from”). © by Pearson Education, Inc. All Rights Reserved.
27
10.3.1 Creating Base Class CommissionEmployee
So, the beginning of class CommissionEmployee could have been written as Public Class CommissionEmployee Inherits Object You typically do not include “Inherits Object” in your code, since it’s implied. Class CommissionEmployee inherits the methods of class Object—class Object does not have any fields. One of the methods inherited from class Object is ToString, so every class has a ToString method that returns a String representation of the object on which it’s called. We discuss the default behavior of method ToString momentarily. © by Pearson Education, Inc. All Rights Reserved.
28
10.3.1 Creating Base Class CommissionEmployee
CommissionEmployee Constructor Constructors are not inherited, so class CommissionEmployee does not inherit class Object’s constructor. However, class CommissionEmployee’s constructor (lines 11–20) calls Object’s constructor implicitly. In fact, the first task of any derived-class constructor is to call its direct base class’s constructor, either explicitly or implicitly (if no constructor call is specified), to ensure that the instance variables declared in the base class are initialized properly. © by Pearson Education, Inc. All Rights Reserved.
29
10.3.1 Creating Base Class CommissionEmployee
The syntax for calling a base-class constructor explicitly is discussed in Section If the code does not include an explicit call to the base-class constructor, Visual Basic implicitly calls the base class’s default or parameterless constructor. The comment in line 14 of Fig. 10.4 indicates where the implicit call to the base class Object’s default constructor occurs (you do not need to write the code for this call). Object’s default constructor does nothing. Even if a class does not have constructors, the default constructor that the compiler implicitly creates for the class will call the base class’s default or parameterless constructor. After the implicit call to Object’s constructor occurs, lines 15– 19 assign values to the class’s properties. © by Pearson Education, Inc. All Rights Reserved.
30
10.3.1 Creating Base Class CommissionEmployee
Method CalculateEarnings and Declaring Methods Overridable Method CalculateEarnings (lines 55–57) calculates a CommissionEmployee’s earn-ings. Line 56 multiplies the CommissionRate by the GrossSales and returns the result. A base-class method must be declared Overridable if a derived class should be allowed to override the method with a version more appropriate for that class. © by Pearson Education, Inc. All Rights Reserved.
31
10.3.1 Creating Base Class CommissionEmployee
When we create class BasePlusCommissionEmployee, we’ll want to override (redefine) CommissionEmployee’s Calculate-Earnings method to customize the earnings calculation for a BasePlusCommissionEmployee. For this reason, we declared CalculateEarnings as Overridable in line 55. In BasePlusCommissionEmployee, we’ll declare method CalculateEarnings with the keyword Overrides. © by Pearson Education, Inc. All Rights Reserved.
32
10.3.1 Creating Base Class CommissionEmployee
Method ToString and Overriding Base Class Methods Method ToString (lines 60–66) returns a String containing information about the CommissionEmployee. The keyword Overrides (line 60) indicates that this method overrides (redefines) the version of ToString that was inherited from CommissionEmployee’s base class (that is, Object). © by Pearson Education, Inc. All Rights Reserved.
33
10.3.1 Creating Base Class CommissionEmployee
In class Object, method ToString is declared as: Public Overridable Function ToString() As String so that ToString can be overridden in any derived class. If you do not override ToString in class CommissionEmployee, the default implementation inherited from class Object would return only "ProjectName.CommissionEmployee"—for this example, we named the project InheritanceTest. © by Pearson Education, Inc. All Rights Reserved.
34
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Most of a BasePlusCommissionEmployee’s capabilities are similar, if not identical, to the those of class CommissionEmployee (Fig. 10.4). Both classes require instance variables for the first name, last name, social security number, gross sales and commission rate, and properties and methods to manipulate that data. To create class BasePlusCommissionEmployee without using inheritance, we probably would have copied the code from class CommissionEmployee and pasted it into class BasePlusCommissionEmployee, then modified the new class to include a base salary instance variable, and the methods and properties that manipulate the base salary, including a new CalculateEarnings method. © by Pearson Education, Inc. All Rights Reserved.
35
10.3.2 Creating Derived Class BasePlusCommissionEmployee
This copy-and-paste approach is often error prone and time consuming. Worse yet, it can spread many physical copies of the same code (including errors) throughout a system, creating a code-maintenance nightmare. Is there a way to “absorb” the instance variables and methods of one class in a way that makes them part of another class without duplicating code? Indeed there is—using the elegant object-oriented programming technique of inheritance. © by Pearson Education, Inc. All Rights Reserved.
36
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
37
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Declaring Class BasePlusCommissionEmployee We now discuss the second part of our introduction to inheritance by declaring the derived class BasePlusCommissionEmployee (Fig. 10.5), which inherits most of its capabilities from class CommissionEmployee (line 4). A BasePlusCommissionEmployee is a CommissionEmployee (because inheritance passes on the capabilities of class CommissionEmployee), but class BasePlusCommissionEmployee also has instance variable baseSalaryValue (line 6) property BaseSalary (lines 19–32). © by Pearson Education, Inc. All Rights Reserved.
38
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Also, BasePlusCommissionEmployee provides a constructor (lines 9–16) a customized version of method CalculateEarnings (lines 35–37) a customized version of method ToString (lines 40–43). © by Pearson Education, Inc. All Rights Reserved.
39
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
40
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
41
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
42
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Inheriting from Class CommissionEmployee Keyword Inherits in line 4 of the class declaration indicates that class BasePlusCommissionEmployee inherits all of the Public members (and, as we’ll soon see, Protected members if there were any) of class CommissionEmployee. We do not redeclare the base class’s Private instance variables—these are nevertheless present (but hidden) in derived class objects. Even though they’re present, they’re declared Private in the base class, so as we’ll see in a moment, we’ll have to make special provision to access this base-class information from the derived class. © by Pearson Education, Inc. All Rights Reserved.
43
10.3.2 Creating Derived Class BasePlusCommissionEmployee
The CommissionEmployee constructor is not inherited. Thus, the Public services of BasePlusCommissionEmployee include its constructor (lines 9–16) the Public methods and properties inherited from class CommissionEmployee property BaseSalary (lines 19–32), which cannot be auto- implemented because it performs validation in its Set accessor method CalculateEarnings (lines 35–37) method ToString (lines 40–43). © by Pearson Education, Inc. All Rights Reserved.
44
10.3.2 Creating Derived Class BasePlusCommissionEmployee
BasePlusCommissionEmployee Constructor Each derived-class constructor must implicitly or explicitly call its base-class constructor to ensure that the instance variables inherited from the base class are properly initialized. BasePlusCommissionEmployee’s six-argument constructor (lines 9–16) explicitly calls class CommissionEmployee’s five-argument constructor (line 14) to initialize the base class portion of a BasePlusCommissionEmployee object (that is, the five instance variables from class CommissionEmployee). © by Pearson Education, Inc. All Rights Reserved.
45
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Line 14 uses the base-class constructor call syntax— keyword MyBase, followed by the dot (.) separator, followed by New and a set of parentheses containing the arguments to the base-class constructor—first, last, ssn, sales and rate. Then, line 15 initializes the BasePlusCommissionEmployee’s base salary. If the BasePlusCommissionEmployee constructor did not include line 14, Visual Basic would attempt to invoke class CommissionEmployee’s parameterless or default constructor, which does not exist, so a compilation error would occur. The explicit base-class constructor call (line 14) must be the first statement in the derived-class constructor’s body. © by Pearson Education, Inc. All Rights Reserved.
46
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Overriding Method CalculateEarnings Class BasePlusCommissionEmployee’s CalculateEarnings method (lines 35–37) overrides class CommissionEmployee’s CalculateEarnings method (Fig. 10.4, lines 55–57) to calculate the earnings of a base- salaried commission employee. The new version obtains the portion of the employee’s earnings based on commission alone by calling CommissionEmployee’s CalculateEarnings method with the expression MyBase.CalculateEarnings() (line 36). © by Pearson Education, Inc. All Rights Reserved.
47
10.3.2 Creating Derived Class BasePlusCommissionEmployee
BasePlusCommissionEmployee’s CalculateEarnings method then adds the BaseSalary to this value to calculate the total earnings of the derived-class employee. Note the syntax used to invoke an overridden base-class method from a derived class—place the keyword MyBase and a dot (.) separator before the base-class method name. By having BasePlusCommissionEmployee’s Calculate-Earnings method invoke CommissionEmployee’s CalculateEarnings method to calculate part of a BasePlusCommissionEmployee object’s earnings, we avoid duplicating the code and reduce code- maintenance problems. © by Pearson Education, Inc. All Rights Reserved.
48
10.3.2 Creating Derived Class BasePlusCommissionEmployee
Overriding Method ToString BasePlusCommissionEmployee’s ToString method (lines 40–43) overrides class CommissionEmployee’s ToString method (Fig. 10.4, lines 60–66) to return a String representation that’s appropriate for a BasePlusCommissionEmployee. The derived class creates part of a BasePlusCommissionEmployee object’s String representation by concatenating "base-plus-" with the String returned by calling CommissionEmployee’s ToString method via the expression MyBase.ToString() (line 41). © by Pearson Education, Inc. All Rights Reserved.
49
10.3.2 Creating Derived Class BasePlusCommissionEmployee
BasePlusCommissionEmployee’s ToString method then concatenates the remainder of a BasePlusCommissionEmployee object’s String representation (that is, the value of class BasePlusCommissionEmployee’s base salary) before returning the String. © by Pearson Education, Inc. All Rights Reserved.
50
10.3.3 Testing Class BasePlusCommissionEmployee
Figure 10.6 tests class BasePlusCommissionEmployee. Lines 9–10 create a BasePlusCommissionEmployee object and pass "Bob", "Lewis", " ", 5000, and 300 to the constructor as the first name, last name, social security number, gross sales, commission rate and base salary, respectively. Lines 13–22 use BasePlusCommissionEmployee’s properties to output the object’s data. Notice that we’re able to access all of the Public properties of classes CommissionEmployee and BasePlusCommissionEmployee here. Lines 25–26 calculate and display the BasePlusCommissionEmployee’s earnings by calling its Caculate-Earnings method. © by Pearson Education, Inc. All Rights Reserved.
51
10.3.3 Testing Class BasePlusCommissionEmployee
Because this method is called on a BasePlusCommissionEmployee object, the derived- class version of the method executes. Next, lines 29–31 modify the GrossSales, CommissionRate and BaseSalary properties. Lines 34–36 output the updated data—this time by calling the BasePlusCommissionEmployee’s ToString method. Again, because this method is called on a BasePlusCommissionEmployee object, the derived class version of the method executes. Finally, lines 39–40 calculate and display the BasePlusCommissionEmployee’s updated earnings. © by Pearson Education, Inc. All Rights Reserved.
52
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
53
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
54
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
55
10.4 Constructors in Derived Classes
Creating a derived-class object begins a chain of constructor calls in which the derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor either explicitly (via the MyBase reference) or implicitly (calling the base class’s default or parameterless constructor). Similarly, if the base class is derived from another class (as is every class except Object), the base-class constructor invokes the constructor of the next class up the hierarchy, and so on. © by Pearson Education, Inc. All Rights Reserved.
56
10.4 Constructors in Derived Classes
The last constructor called in the chain is always the constructor for class Object. The original derived-class constructor’s body finishes executing last. Each base class’s constructor manipulates the base- class instance variables that are part of the derived- class object. For example, let’s reconsider the CommissionEmployee– BasePlusCommissionEmployee hierarchy from Figs. 10.4 and 10.5. © by Pearson Education, Inc. All Rights Reserved.
57
10.4 Constructors in Derived Classes
When a program creates a BasePlusCommissionEmployee object (Fig. 10.6, lines 9–10), the BasePlusCommissionEmployee constructor is called. That constructor, before executing its full body code, immediately calls CommissionEmployee’s constructor (Fig. 10.5, line 14), which in turn calls Object’s constructor. © by Pearson Education, Inc. All Rights Reserved.
58
10.4 Constructors in Derived Classes
Class Object’s constructor has an empty body, so it immediately returns control to the Commission- Employee’s constructor, which then initializes the Private instance variables of CommissionEmployee (Fig. 10.4, lines 15–19) that are part of the BasePlusCommissionEmployee object. When the CommissionEmployee’s constructor completes execution, it returns control to the BasePlus- CommissionEmployee’s constructor, which initializes the BasePlusCommissionEmployee object’s baseSalaryValue (via property BaseSalary; Fig. 10.5, line 15). © by Pearson Education, Inc. All Rights Reserved.
59
10.5 Protected Members This section introduces the access modifier Protected. A base class’s Protected members can be accessed only by members of that base class and by members of its derived classes. In inheritance, 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. A base class’s Private members are not inherited by its derived classes. © by Pearson Education, Inc. All Rights Reserved.
60
10.5 Protected Members Derived-class methods can refer to Public and Protected members inherited from the base class simply by using the member names. Derived-class methods cannot directly access Private members of their base class. A derived class can change the state of Private base- class instance variables only through Public and Protected methods provided in the base class and inherited by the derived class. In most cases, it’s better to use Private instance variables to encourage proper software engineering. © by Pearson Education, Inc. All Rights Reserved.
61
10.5 Protected Members Your code will be easier to maintain, modify and debug. Using Protected instance variables creates several potential problems. First, the derived-class object can set an inherited variable’s value directly without using a Set accessor. Therefore, a derived-class object can assign an invalid value to the variable. Another problem with using Protected instance variables is that derived-class methods are more likely to be written so that they depend on the base class’s data implementation. In practice, derived classes should depend only on the base-class services (that is, non-Private methods and properties) and not on the base-class data implementation. © by Pearson Education, Inc. All Rights Reserved.
62
10.5 Protected Members With Protected instance variables in the base class, all the derived classes of the base class may need to be modified if the base-class implementation changes. In such a case, the software is said to be brittle, because a small change in the base class can “break” derived- class implementations. You should be able to change the base-class implementation while still providing the same services to the derived classes. Of course, if the base-class services change, you must reimplement the derived classes. © by Pearson Education, Inc. All Rights Reserved.
63
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
64
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
65
10.6 Introduction to Polymorphism: Polymorphic Video Game
Suppose we design a video game that manipulates objects of many different types, including objects of classes Martian, Venutian, Plutonian, SpaceShip and La-serBeam. Imagine that each class inherits from the common base class called SpaceObject, which contains method Draw. Each derived class implements this method in a manner appropriate to that class. A screen-manager program maintains a collection (for example, a SpaceObject array) of references to objects of the various classes. © by Pearson Education, Inc. All Rights Reserved.
66
10.6 Introduction to Polymorphism: Polymorphic Video Game
To refresh the screen, the screen manager periodically sends each object the same message, Draw. However, each object responds in a unique way. For example, a Martian object might draw itself in red with the appropriate number of antennae. A SpaceShip object might draw itself as a bright silver flying saucer. A LaserBeam object might draw itself as a bright red beam across the screen. The same message (in this case, Draw) sent to a variety of objects has many forms of results, hence the term polymorphism. © by Pearson Education, Inc. All Rights Reserved.
67
10.6 Introduction to Polymorphism: Polymorphic Video Game
A screen manager might use polymorphism to make the system extensible and facilitate adding new classes to a system with minimal modifications to the system’s code. Suppose that we want to add Mercurian objects to our video game. To do so, we must build a class Mercurian that inherits from SpaceObject and provides its own Draw method implementation. © by Pearson Education, Inc. All Rights Reserved.
68
10.6 Introduction to Polymorphism: Polymorphic Video Game
When objects of class Mercurian appear in the SpaceObject collection, the screen-manager code invokes method Draw, exactly as it does for the other objects in the collection, regardless of their types. So the new Mercurian class simply plugs right in without any modification of the screen-manager code by the programmer. Thus, without modifying the system (other than to build new classes and modify the code that creates new objects), programmers can use polymorphism to include types that were not envisioned when the system was created. © by Pearson Education, Inc. All Rights Reserved.
69
10.7 Abstract Classes and Methods
When we think of a class type, we assume that programs will create objects of that type. In some cases, however, it’s useful to declare classes for which you never intend to instantiate objects. Such classes are called abstract classes. Because they’re used only as base classes in inheritance hierarchies, we refer to them as abstract base classes. These classes cannot be used to instantiate objects, because, as you’ll soon see, abstract classes are incomplete. We demonstrate abstract classes in Section 10.8. © by Pearson Education, Inc. All Rights Reserved.
70
10.7 Abstract Classes and Methods
The purpose of an abstract class is primarily to provide an appropriate base class from which other classes can inherit and thus share a common design. In the Shape hierarchy of Fig. 10.3, for example, derived classes inherit the notion of what it means to be a Shape—possibly including common properties such as Location, Color and Border-Thickness, and behaviors such as Draw, Move, Resize and ChangeColor. © by Pearson Education, Inc. All Rights Reserved.
71
10.7 Abstract Classes and Methods
Classes that can be used to instantiate objects are called concrete classes. Such classes provide implementations of every method they declare (some of the implementations can be inherited). For example, we could derive concrete classes Circle, Square and Triangle from abstract base class TwoDimensionalShape. Similarly, we could derive concrete classes Sphere, Cube and Tetrahedron from abstract base class ThreeDimensionalShape. © by Pearson Education, Inc. All Rights Reserved.
72
10.7 Abstract Classes and Methods
Abstract base classes are too general to create real objects— they specify only what is common among derived classes. We need to be more specific before we can create objects. For example, if you send the Draw message to abstract class TwoDimensionalShape, it knows that two- dimensional shapes should be drawable, but it does not know what specific shape to draw, so it cannot implement a real Draw method. Concrete classes provide the specifics that make it reasonable to instantiate objects. © by Pearson Education, Inc. All Rights Reserved.
73
10.7 Abstract Classes and Methods
Declaring Abstract Classes and Abstract Methods You make a class abstract by declaring it with keyword MustInherit. An abstract class normally contains one or more abstract methods. An abstract method is declared with keyword MustOverride, as in Public MustOverride Sub Draw() ' abstract method © by Pearson Education, Inc. All Rights Reserved.
74
10.7 Abstract Classes and Methods
MustOverride methods do not provide implementations. A class that contains any MustOverride methods must be declared as a MustInherit class even if it contains some concrete methods. Each concrete derived class of a MustInherit base class must provide concrete implementations of all the base class’s MustOverride methods. Constructors and Shared methods cannot be overridden, so they cannot be declared MustOverride. © by Pearson Education, Inc. All Rights Reserved.
75
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
76
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
77
10.8 Case Study: Payroll System Class Hierarchy Using Polymorphism
Let’s reexamine the CommissionEmployee– BasePlusCommissionEmployee hierarchy that we explored in Section 10.3. Now we use an abstract method and polymorphism to perform payroll calculations based on the type of employee. We create an enhanced employee hierarchy to solve the following problem: A company pays its employees on a weekly basis. The employees are of three types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, commission employees are paid a percentage of their sales, and base-plus-commission employees receive a base salary plus a percentage of their sales. The company wants to implement an application that performs its payroll calculations polymorphically. © by Pearson Education, Inc. All Rights Reserved.
78
10.8 Case Study: Payroll System Class Hierarchy Using Polymorphism
We use abstract (that is, Employee) class Employee to represent the general concept of an employee. The classes that inherit from Employee are SalariedEmployee and CommissionEmployee. Class BasePlusCommissionEmployee inherits from Commission-Employee. The UML class diagram in Fig. 10.7 shows our polymorphic employee inheritance hierarchy. Abstract class name Employee is italicized, as per UML convention; concrete class names are not italicized. © by Pearson Education, Inc. All Rights Reserved.
79
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
80
10.8 Case Study: Payroll System Class Hierarchy Using Polymorphism
The following five sections implement the Employee class hierarchy. The first four sections show the abstract base class Employee and the concrete derived classes SalariedEmployee, CommissionEmployee, and the indirectly derived concrete class BasePlusCommissionEmployee. The last section shows a test program that builds objects of these classes and processes them polymorphically. © by Pearson Education, Inc. All Rights Reserved.
81
10.8.1 Abstract Base Class Employee
Abstract base class Employee declares the set of methods that a program can invoke on all employees. Each employee, regardless of the way his or her earnings are calculated, has a first name, a last name and a social security number. So Public properties FirstName, LastName and SocialSecurityNumber will appear in abstract base class Employee. Class Employee also provides methods CalculateEarnings and ToString. © by Pearson Education, Inc. All Rights Reserved.
82
10.8.1 Abstract Base Class Employee
Method CalculateEarnings certainly applies to all employees, but each specific earnings calculation depends on the employee’s class. So we declare the method as MustOverride in base class Employee because a default implementation does not make sense for that method—there is not enough information to determine what amount CalculateEarnings should return for a general Employee. Each derived class Overrides CalculateEarnings with an appropriate specific implementation. © by Pearson Education, Inc. All Rights Reserved.
83
10.8.1 Abstract Base Class Employee
In the test program, we’ll maintain an array of Employee variables, each holding a reference to an Employee object. Of course, there cannot be Employee objects because Employee is an abstract class—thanks to inheritance, however, all objects of all derived classes of Employee may be thought of as Employee objects. Although we cannot instantiate objects of abstract base classes, we can use abstract base class variables to refer to objects of any concrete classes derived from those abstract classes. Programs typically use such variables to manipulate derived-class objects polymorphically. © by Pearson Education, Inc. All Rights Reserved.
84
10.8.1 Abstract Base Class Employee
The program we build in Fig. 10.13 iterates through an array of Employee variables and calls CalculateEarnings for each Employee object. These method calls are processed polymorphically. Including the abstract method CalculateEarnings in class Employee forces every directly derived concrete class of Employee to override CalculateEarnings. Method ToString in class Employee returns a String containing the first name, last name and social security number of the employee. © by Pearson Education, Inc. All Rights Reserved.
85
10.8.1 Abstract Base Class Employee
Each derived class of Employee will override method ToString to create a String representation of an object of that class that contains the employee’s type (for example, "salaried employee:") followed by the rest of the employee’s information. Fig. 10.8 shows the four classes of the hierarchy of Fig. 10.7 down the left side and methods CalculateEarnings and ToString across the top. For each class, the diagram shows the desired results of each method. © by Pearson Education, Inc. All Rights Reserved.
86
10.8.1 Abstract Base Class Employee
[Note: We do not list base class Employee’s properties because they’re not overridden in any of the derived classes—each of these properties is inherited and used “as is” by each of the derived classes.] Class Employee (Fig. 10.9) is a MustInherit class, meaning it can be used only as an abstract base class. © by Pearson Education, Inc. All Rights Reserved.
87
10.8.1 Abstract Base Class Employee
The class includes a constructor that takes the first name, last name and social security number as arguments (lines 9–14) properties for the first name, last name and social security number (lines 4–6) method ToString (lines 17–20), which returns the String representation of an Employee MustOverride (abstract) method Calculate- Earnings (line 23), which must be implemented by concrete derived classes. © by Pearson Education, Inc. All Rights Reserved.
88
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
89
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
90
10.8.1 Abstract Base Class Employee
Why did we decide to declare CalculateEarnings as a MustOverride method? It simply does not make sense to provide an implementation of this method in class Employee. We cannot calculate the earnings for a general Employee—we first must know the specific Employee type to determine the appropriate earnings calculation. By declaring this method MustOverride, we indicate that every concrete derived class must provide an appropriate CalculateEarnings implementation that Overrides the base class method, and that a program will be able to use base- class Employee variables to invoke method CalculateEarnings polymorphically for every type of Employee. © by Pearson Education, Inc. All Rights Reserved.
91
10.8.2 Concrete Derived Class SalariedEmployee
Class SalariedEmployee (Fig. 10.10) inherits from class Employee (line 4) and overrides Calculate-Earnings (lines 33–35), which makes SalariedEmployee a concrete class. The class includes a constructor (lines 9–14) that takes a first name, a last name, a social security number and a weekly salary as arguments a WeeklySalary property that has a Get accessor (lines 18–20) to return weekly-SalaryValue’s value and a Set accessor (lines 22–29) to assign a new nonnegative value to instance variable weeklySalaryValue a method CalculateEarnings (lines 33–35) to calculate a SalariedEmployee’s earnings a method ToString (lines 38–42) that returns a String including the employee’s type, namely, "salaried employee:", followed by employee- specific information produced by base class Employee’s ToString method, and the value of Salaried-Employee’s WeeklySalary property. © by Pearson Education, Inc. All Rights Reserved.
92
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
93
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
94
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
95
10.8.2 Concrete Derived Class SalariedEmployee
Class SalariedEmployee’s constructor passes the first name, last name and social security number to base class Employee’s constructor (line 12). Method CalculateEarnings overrides abstract method CalculateEarnings of Employee with a concrete implementation that returns the SalariedEmployee’s weekly salary. SalariedEmployee’s ToString method (lines 38–42) overrides Employee method ToString. © by Pearson Education, Inc. All Rights Reserved.
96
10.8.2 Concrete Derived Class SalariedEmployee
If class SalariedEmployee did not override ToString, the class would have inherited Employee’s ToString method. In that case, SalariedEmployee’s ToString method would simply return the employee’s full name and social security number, which does not fully represent a SalariedEmployee. © by Pearson Education, Inc. All Rights Reserved.
97
10.8.2 Concrete Derived Class SalariedEmployee
To produce a complete String representation of a SalariedEmployee, the derived class’s ToString method returns "salaried employee:" followed by the base-class Employee- specific information (that is, first name, last name and social security number) obtained by invoking the base class’s ToString method (line 41)—a nice example of code reuse. The String representation of a Salaried- Employee also contains the employee’s weekly salary obtained from the Weekly-Salary property. © by Pearson Education, Inc. All Rights Reserved.
98
10.8.3 Concrete Derived Class CommissionEmployee
Class CommissionEmployee (Fig. 10.11) inherits from class Employee (line 4); therefore, CommissionEmployee no longer declares the properties that are declared in base class Employee. The class includes a constructor (lines 10–16) that takes a first name, a last name, a social security number, a sales amount and a commission rate Get accessors (lines 20–22 and 36–38) that retrieve the values of instance variables grossSalesValue and commissionRateValue, respectively Set accessors (lines 24–31 and 40–47) that assign validated new values to these instance variables method CalculateEarnings (lines 51–53) to calculate a CommissionEmployee’s earnings method ToString (lines 56–60), which returns the employee’s type, namely, "commission employee:" and employee-specific information, including the full name and social security number, and the values of properties GrossSales and CommissionRate. © by Pearson Education, Inc. All Rights Reserved.
99
10.8.3 Concrete Derived Class CommissionEmployee
The CommissionEmployee’s constructor passes the first name, last name and social security number to the Employee constructor (line 13) to initialize Employee’s Private instance variables. Method ToString calls base-class method ToString (line 59) to obtain the Employee-specific information (that is, first name, last name and social security number). © by Pearson Education, Inc. All Rights Reserved.
100
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
101
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
102
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
103
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
104
10.8.4 Indirect Concrete Derived Class BasePlusCommissionEmployee
Class BasePlusCommissionEmployee (Fig. 10.12) inherits class CommissionEmployee (line 4) and therefore is an indirect derived class of class Employee. Class BasePlusCommissionEmployee has a constructor (lines 9–16) that takes as arguments a first name, a last name, a social security number, a sales amount, a commission rate and a base salary—the first five are passed to the CommissionEmployee constructor (line 14) to initialize the inherited members a property BaseSalary whose Set accessor (lines 24–31) assigns a validated new value to instance variable baseSalaryValue, and whose Get accessor (lines 20–22) returns baseSalaryValue © by Pearson Education, Inc. All Rights Reserved.
105
10.8.4 Indirect Concrete Derived Class BasePlusCommissionEmployee
method CalculateEarnings (lines 35–37) which calculates a BasePlusCommissionEmployee’s earn-ings—line 36 calls base-class CommissionEmployee’s Calculate-Earnings method to calculate the commission-based portion of the employee’s earnings (another nice example of code reuse) method ToString (lines 40–43) which creates a String representation of a BasePlusCommissionEmployee that contains "base-plus-", followed by the String obtained by invoking base-class CommissionEmployee’s ToString method (another nice example of code reuse), then the base salary. Recall that CommissionEmployee’s ToString method calls Employee’s ToString method, so BasePlusCommissionEmployee’s ToString initiates a chain of method calls that spans all three levels of the Employee hierarchy. © by Pearson Education, Inc. All Rights Reserved.
106
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
107
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
108
10.8.5 Demonstrating Polymorphic Processing
To test our Employee hierarchy, the program in Fig. creates an object of each of the three concrete classes SalariedEmployee, CommissionEmployee and BasePlusCommissionEmployee. The program manipulates these objects, first via variables of each object’s own type, then polymorphically, using an array of Employee variables. Lines 8–13 create an object of each of the three concrete Employee- derived classes. Lines 16–26 display (nonpolymorphically) the String representation and earnings of each of these objects in outputTextBox1. © by Pearson Education, Inc. All Rights Reserved.
109
10.8.5 Demonstrating Polymorphic Processing
Creating an Array of Abstract Base Class Employee Variables Lines 29–30 create and initialize array employees with three Employees. This statement is valid because, through inheritance, a SalariedEmployee is an Employee, a CommissionEmployee is an Employee and a BasePlusCommissionEmployee is an Employee. Therefore, we can assign the references of SalariedEmployee, CommissionEmployee and BasePlusCommissionEmployee objects to base-class Employee variables, even though Employee is a MustInherit (abstract) class. © by Pearson Education, Inc. All Rights Reserved.
110
10.8.5 Demonstrating Polymorphic Processing
Polymorphically Processing Employees Lines 36–41 iterate through array employees and invoke methods ToString (line 39) and CalculateEarnings (line 40) with Employee variable currentEmployee, which is assigned the reference to a different Employee in the array during each iteration. The output displayed- in outputTextBox2 illustrates that the appropriate methods for each class are indeed invoked— you can compare the results in outputTextBox2 with the non-polymorphic results in outputTextBox1 to see that they’re identical. © by Pearson Education, Inc. All Rights Reserved.
111
10.8.5 Demonstrating Polymorphic Processing
All calls to methods ToString and CalculateEarnings are resolved polymorphically at execution time, based on the type of the object to which currentEmployee refers. This process is known as late binding. For example, line 39 explicitly invokes method ToString of the object to which currentEmployee refers. As a result of late binding, the proper ToString method to call is decided at execution time rather than at compile time. © by Pearson Education, Inc. All Rights Reserved.
112
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
113
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
114
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
115
10.9 Online Case Study: Interfaces
The book’s Companion Website ( provides an introduction to interfaces. An interface describes a set of methods that can be called on an object but it does not provide concrete implementations for the methods. Programmers can declare classes that implement (that is, declare the methods of) one or more interfaces. Each interface method must be declared in all the classes that implement the interface. Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all derived classes of that class as well. © by Pearson Education, Inc. All Rights Reserved.
116
10.9 Online Case Study: Interfaces
Interfaces are particularly useful for assigning common functionality to possibly unrelated classes. This allows objects of unrelated classes to be processed polymorphically—objects of classes that implement the same interface can respond to the same method calls. To demonstrate creating and using interfaces, we modify our payroll application to create a general accounts payable application that can calculate payments due not only for company employees, but also for invoice amounts to be billed for purchased goods. © by Pearson Education, Inc. All Rights Reserved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.