Visual C# How To Program, Global Edition - (12 OOP Polymorphism and Interfaces 508)
Visual C# How To Program, Global Edition - (12 OOP Polymorphism and Interfaces 508)
Interface Description
IDisposable Implemented by classes that must provide an explicit mechanism for releasing
resources. Some resources can be used by only one program at a time. In addi-
tion, some resources, such as files on disk, are unmanaged resources that, unlike
memory, cannot be released by the garbage collector. Classes that implement
interface IDisposable provide a Dispose method that can be called to explicitly
release resources that are explicitly associated with an object. We discuss IDis-
posable briefly in Chapter 13, Exception Handling: A Deeper Look. You can
learn more about this interface at http://msdn.microsoft.com/library/
system.idisposable. The MSDN article Implementing a Dispose Method at
http://msdn.microsoft.com/library/fs2xkftw discusses the proper imple-
mentation of this interface in your classes.
IEnumerator Used for iterating through the elements of a collection (such as an array or a
List) one element at a time—the foreach statement uses an IEnumerator object
to iterate through elements. Interface IEnumerator contains method MoveNext
to move to the next element in a collection, method Reset to move to the posi-
tion before the first element and property Current to return the object at the
current location. We use IEnumerator in Chapter 21. All IEnumberable objects
(Chapter 9) provide a GetEnumerator method that returns an IEnumerator
object.
Fig. 12.15 | Common interfaces of the .NET Framework Class Library. (Part 2 of 2.)
12.8 Wrap-Up
This chapter introduced polymorphism—the ability to process objects that share the same
base class in a class hierarchy as if they were all objects of the base class. The chapter dis-
Copyright © 2017. Pearson Education, Limited. All rights reserved.
cussed how polymorphism makes systems extensible and maintainable, then demonstrated
how to use overridden methods to effect polymorphic behavior. We introduced the notion
of an abstract class, which allows you to provide an appropriate base class from which other
classes can inherit. You learned that an abstract class can declare abstract methods that each
derived class must implement to become a concrete class. We also discussed that an app
can use variables of an abstract class to invoke concrete derived-class implementations of
abstract methods polymorphically. You also learned how to determine an object’s type
at execution time. We showed how to create sealed methods and classes. Finally, the
chapter discussed declaring and implementing an interface as another way to achieve poly-
morphic behavior, often among objects of different, unrelated classes.
You should now be familiar with classes, objects, encapsulation, inheritance, inter-
faces and polymorphism—the most essential aspects of object-oriented programming.
Next, we take a deeper look at using exception handling to deal with runtime errors.
Summary
Section 12.1 Introduction
• With polymorphism, we can design and implement systems that are easily extensible—new class-
es can be added with little or no modification to the general portions of the app.
Deitel, H., Deitel, P., Deitel, H., & Deitel, P. (2017). Visual c# how to program, global edition. Pearson Education, Limited.
Created from deakin on 2024-09-09 07:50:24.
Summary 543
the reference-type variable refers. This process is known as dynamic binding or late binding.
• The is operator determines whether the type of the object in the left operand matches the type
specified by the right operand and returns true if the two have an is-a relationship.
• The as operator performs a downcast that returns a reference to the appropriate object if the
downcast is successful and returns null if the downcast fails.
• A base-class reference can be used to invoke only the methods declared in the base class. If an app
needs to perform a derived-class-specific operation on a derived-class object referenced by a base-
class variable, the app must first downcast the base-class reference to a derived-class reference.
• Every object knows its own type and can access this information through method GetType, which
all classes inherit from class object.
• Assigning a base-class reference to a derived-class variable is not allowed without an explicit cast
or without using the as operator. The is operator can be used to ensure that such a cast is per-
formed only if the object is a derived-class object.
Terminology
abstract class interface declaration
abstract keyword interface inheritance
abstract method interface keyword
abstract operation is-a relationship
Copyright © 2017. Pearson Education, Limited. All rights reserved.
as operator is operator
base-class reference late binding
concrete class polymorphism
derived-class reference realization
downcasting sealed class
dynamic binding sealed method
GetType method of class object static binding
implement an interface Type class
inlining code
Self-Review Exercises
12.1 Fill in the blanks in each of the following statements:
a) If a class contains at least one abstract method, it must be declared as a(n) class.
b) Classes from which objects can be instantiated are called classes.
c) involves using a base-class variable to invoke methods on base-class and de-
rived-class objects, enabling you to “program in the general.”
d) Methods in a class that do not provide implementations must be declared using key-
word .
e) Casting a reference stored in a base-class variable to a derived-class type is called
.
Deitel, H., Deitel, P., Deitel, H., & Deitel, P. (2017). Visual c# how to program, global edition. Pearson Education, Limited.
Created from deakin on 2024-09-09 07:50:24.
Answers to Self-Review Exercises 545
12.2 State whether each of the statements that follows is true or false. If false, explain why.
a) It’s possible to treat base-class objects and derived-class objects similarly.
b) All methods in an abstract class must be declared as abstract methods.
c) Attempting to invoke a derived-class-only method through a base-class variable is an error.
d) If a base class declares an abstract method, a derived class must implement that method.
e) An object of a class that implements an interface may be thought of as an object of that
interface type.
Exercises
12.3 (Key Feature of OOP) One of the key features of object-oriented programming is polymor-
phism. What does polymorphism mean? Does this require altering the whole app, if some new class-
es are added to the app?
12.4 (Sealed Method) A sealed method’s declaration can never change. Do all derived classes use
the same method implementation? What term is used to describe this? How does the compiler op-
timize the code in this case?
12.5 (Abstract Properties) An abstract class can have abstract methods in it. Can properties, like
get and set, be declared as abstract? Explain.
12.6 (Polymorphism and Extensibility) How does polymorphism promote extensibility?
12.7 (Polymorphism and device drivers) How is polymorphism effective for implementing
device drivers in layered software systems?
Copyright © 2017. Pearson Education, Limited. All rights reserved.
12.8 (Interface in UML) An interface in a class is listed by its name after a colon (:) in the class
declaration. How is it distinguished in a UML diagram?
12.9 (Payroll System Modification) Modify the payroll system of Figs. 12.4–12.9 to include pri-
vate instance variable birthDate in class Employee. Use class Date of Fig. 10.7 to represent an em-
ployee’s birthday. Assume that payroll is processed once per month. Create an array of Employee
variables to store references to the various employee objects. In a loop, calculate the payroll for each
Employee (polymorphically), and add a $100.00 bonus to the person’s payroll amount if the current
month is the month in which the Employee’s birthday occurs.
12.10 (Shape Hierarchy) Implement the Shape hierarchy of Fig. 11.3. Omit the Triangle and
Tetrahedron classes. Each TwoDimensionalShape should contain read-only abstract property Area
to calculate the area of the two-dimensional shape. Each ThreeDimensionalShape should have read-
only abstract properties Area and Volume to calculate the surface area and volume, respectively, of
the three-dimensional shape. Create an app that uses an array of Shape references to objects of each
concrete class in the hierarchy. Display a text description of the object to which each array element
refers. Also, in the loop that processes all the shapes in the array, determine whether each shape is a
TwoDimensionalShape or a ThreeDimensionalShape. If a shape is a TwoDimensionalShape, display its
area. If a shape is a ThreeDimensionalShape, display its area and volume.
12.11 (Payroll System Modification) Modify the payroll system of Figs. 12.4–12.9 to include an
additional Employee derived class, PieceWorker, that represents an employee whose pay is based on
the number of pieces of merchandise produced. Class PieceWorker should contain private instance
variables
Deitel, H., Deitel, P., Deitel, H., & Deitel,
wage (to store
P. (2017). the
Visual employee’s
c# how to program, wage per piece)
global edition. Pearsonand
Education,
pieces (to store the number of pieces
Limited.
Created from deakin on 2024-09-09 07:50:24.
546 Chapter 12 OOP: Polymorphism and Interfaces
produced). Provide a concrete implementation of method Earnings in class PieceWorker that cal-
culates the employee’s earnings by multiplying the number of pieces produced by the wage per
piece. Create an array of Employee variables to store references to objects of each concrete class in
the new Employee hierarchy. Display each Employee’s string representation and earnings.
12.12 (Accounts Payable System Modification) Modify the accounts payable app of Figs. 12.11–
12.14 to include the complete functionality of the payroll app of Figs. 12.4–12.9. The app should
still process two Invoice objects, but now should process one object of each of the four Employee
derived classes. If the object currently being processed is a BasePlusCommissionEmployee, the app
should increase the BasePlusCommissionEmployee’s base salary by 10%. Finally, the app should
output the payment amount for each object. Modify PayableInterfaceTest (Fig. 12.14) to poly-
morphically process two Invoices, one SalariedEmployee, one HourlyEmployee, one Commission-
Employee and one BasePlusCommissionEmployee. First, output a string representation of each
IPayable object. Next, if an object is a BasePlusCommissionEmployee, increase its base salary by
10%. Finally, output the payment amount for each IPayable object.
12.13 (Polymorphic Banking Program Using Account Hierarchy) Develop a polymorphic banking
app using the Account hierarchy created in Exercise 11.9. Create an array of Account references to Sav-
ingsAccount and CheckingAccount objects. For each Account in the array, allow the user to specify an
amount of money to withdraw from the Account using method Debit and an amount of money to
deposit into the Account using method Credit. As you process each Account, determine its type. If an
Account is a SavingsAccount, calculate the amount of interest owed to the Account using method Cal-
culateInterest, then add the interest to the account balance using method Credit. After processing
an Account, display the updated account balance obtained by using base-class property Balance.
Making-a-Difference Exercise
12.14 (CarbonFootprint Interface: Polymorphism) Using interfaces, as you learned in this chap-
ter, you can specify similar behaviors for possibly disparate classes. Governments and companies
worldwide are becoming increasingly concerned with carbon footprints (annual releases of carbon
dioxide into the atmosphere) from buildings burning various types of fuels for heat, vehicles burning
fuels for power, and the like. Many scientists blame these greenhouse gases for the phenomenon
Copyright © 2017. Pearson Education, Limited. All rights reserved.
called global warming. Create three small classes unrelated by inheritance—classes Building, Car
and Bicycle. Write an interface ICarbonFootprint with a GetCarbonFootprint method. Have each
of your classes implement that interface, so that its GetCarbonFootprint method calculates an ap-
propriate carbon footprint for that class (check out a few websites that explain how to calculate car-
bon footprints). Write an app that creates objects of each of the three classes, places references to
those objects in List<ICarbonFootprint>, then iterates through the List, polymorphically invoking
each object’s GetCarbonFootprint method.
Deitel, H., Deitel, P., Deitel, H., & Deitel, P. (2017). Visual c# how to program, global edition. Pearson Education, Limited.
Created from deakin on 2024-09-09 07:50:24.