ObjectOriented Programming Inheritance and Polymorphism Visual Basic 2010

Object-Oriented Programming: Inheritance and Polymorphism Visual Basic 2010 How to Program © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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) © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 2 Base Classes and Derived Classes � Community. Member 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Community. Member” 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 2 Base Classes and Derived Classes � So, class Community. Member 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 Community. Member. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Two. Dimensional. Shape and Three. Dimensional. Shape—Shapes are either Two. Dimensional. Shapes or Three. Dimensional. Shapes. ◦ The third level of the hierarchy contains more specific types of Two-Dimensional. Shapes and Three. Dimensional. Shapes. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Two. Dimensional. Shape and is a Shape, while a Sphere is a Three. Dimensional. Shape and is a Shape. � Shape is a direct base class of classes Two. Dimensional. Shape and Three. Dimensional. Shape, and is an indirect base class of all the classes on the third level. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3 Business Case Study: Commission Employees Class Hierarchy � First, we present base class Commission. Employee. � Next, we create a derived class Base. Plus. Commission. Employee that inherits from class Commission. Employee. � Then we present an application that creates a Base. Plus. Commission. Employee object and demonstrates that it has all the capabilities of the base class and the derived class, but calculates its earnings differently. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � Consider class Commission. Employee (Fig. 10. 4). � The Public services of class Commission. Employee include: ◦ a constructor (lines 11– 20) ◦ properties First. Name (line 4), Last. Name (line 5), Social. Security. Number (line 6), Gross. Sales (lines 23– 36) and Commission. Rate (lines 39– 52) ◦ methods Calculate. Earnings (lines 55– 57) and To. String (lines 60– 66). � The class also declares Private instance variables gross. Sales. Value and commission. Rate-Value (lines 7– 8) to represent the employee’s gross sales and commission rate. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � Recall that the compiler automatically generates a Private instance variable for each auto-implemented property, so a Commission. Employee actually has five Private instance variables. � The Set accessors of properties Gross. Sales and Commission. Rate validate their arguments before assigning the values to instance variables gross. Sales. Value and commission. Rate. Value, respectively. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � Properties First. Name, Last. Name and Social. Security. Number 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, 123 -45 -6789 or 123456789). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � 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”). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � So, the beginning of class Commission. Employee could have been written as Public Class Commission. Employee Inherits Object � You typically do not include “Inherits Object” in your code, since it’s implied. � Class Commission. Employee inherits the methods of class Object—class Object does not have any fields. � One of the methods inherited from class Object is To. String, so every class has a To. String method that returns a String representation of the object on which it’s called. � We discuss the default behavior of method To. String momentarily. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � Commission. Employee Constructor ◦ Constructors are not inherited, so class Commission. Employee does not inherit class Object’s constructor. ◦ However, class Commission. Employee’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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � The syntax for calling a base-class constructor explicitly is discussed in Section 10. 3. 2. � 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � Method Calculate. Earnings and Declaring Methods Overridable ◦ Method Calculate. Earnings (lines 55– 57) calculates a Commission. Employee’s earn-ings. ◦ Line 56 multiplies the Commission. Rate by the Gross. Sales 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � When we create class Base. Plus. Commission. Employee, we’ll want to override (redefine) Commission. Employee’s Calculate-Earnings method to customize the earnings calculation for a Base. Plus. Commission. Employee. � For this reason, we declared Calculate. Earnings as Overridable in line 55. � In Base. Plus. Commission. Employee, we’ll declare method Calculate. Earnings with the keyword Overrides. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � Method To. String and Overriding Base Class Methods ◦ Method To. String (lines 60– 66) returns a String containing information about the Commission. Employee. ◦ The keyword Overrides (line 60) indicates that this method overrides (redefines) the version of To. String that was inherited from Commission. Employee’s base class (that is, Object). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 1 Creating Base Class Commission. Employee � In class Object, method To. String is declared as: Public Overridable Function To. String() As String so that To. String can be overridden in any derived class. � If you do not override To. String in class Commission. Employee, the default implementation inherited from class Object would return only "Project. Name. Commission. Employee"—for this example, we named the project Inheritance. Test. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Most of a Base. Plus. Commission. Employee’s capabilities are similar, if not identical, to the those of class Commission. Employee (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 Base. Plus. Commission. Employee without using inheritance, we probably would have copied the code from class Commission. Employee and pasted it into class Base. Plus. Commission. Employee, 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 Calculate. Earnings method. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Declaring Class Base. Plus. Commission. Employee ◦ We now discuss the second part of our introduction to inheritance by declaring the derived class Base. Plus. Commission. Employee (Fig. 10. 5), which inherits most of its capabilities from class Commission. Employee (line 4). ◦ A Base. Plus. Commission. Employee is a Commission. Employee (because inheritance passes on the capabilities of class Commission. Employee), but class Base. Plus. Commission. Employee also has �instance variable base. Salary. Value (line 6) �property Base. Salary (lines 19– 32). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Also, Base. Plus. Commission. Employee provides ◦ a constructor (lines 9– 16) ◦ a customized version of method Calculate. Earnings (lines 35– 37) ◦ a customized version of method To. String (lines 40– 43). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Inheriting from Class Commission. Employee ◦ Keyword Inherits in line 4 of the class declaration indicates that class Base. Plus. Commission. Employee inherits all of the Public members (and, as we’ll soon see, Protected members if there were any) of class Commission. Employee. ◦ 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � The Commission. Employee constructor is not inherited. � Thus, the Public services of Base. Plus. Commission. Employee include its ◦ constructor (lines 9– 16) ◦ the Public methods and properties inherited from class Commission. Employee ◦ property Base. Salary (lines 19– 32), which cannot be autoimplemented because it performs validation in its Set accessor ◦ method Calculate. Earnings (lines 35– 37) ◦ method To. String (lines 40– 43). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Base. Plus. Commission. Employee 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. ◦ Base. Plus. Commission. Employee’s six-argument constructor (lines 9– 16) explicitly calls class Commission. Employee’s five-argument constructor (line 14) to initialize the base class portion of a Base. Plus. Commission. Employee object (that is, the five instance variables from class Commission. Employee). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Line 14 uses the base-class constructor call syntax— keyword My. Base, 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 Base. Plus. Commission. Employee’s base salary. � If the Base. Plus. Commission. Employee constructor did not include line 14, Visual Basic would attempt to invoke class Commission. Employee’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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Overriding Method Calculate. Earnings ◦ Class Base. Plus. Commission. Employee’s Calculate. Earnings method (lines 35– 37) overrides class Commission. Employee’s Calculate. Earnings method (Fig. 10. 4, lines 55– 57) to calculate the earnings of a basesalaried commission employee. ◦ The new version obtains the portion of the employee’s earnings based on commission alone by calling Commission. Employee’s Calculate. Earnings method with the expression My. Base. Calculate. Earnings() (line 36). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Base. Plus. Commission. Employee’s Calculate. Earnings method then adds the Base. Salary 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 My. Base and a dot (. ) separator before the base-class method name. � By having Base. Plus. Commission. Employee’s Calculate-Earnings method invoke Commission. Employee’s Calculate. Earnings method to calculate part of a Base. Plus. Commission. Employee object’s earnings, we avoid duplicating the code and reduce codemaintenance problems. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Overriding Method To. String ◦ Base. Plus. Commission. Employee’s To. String method (lines 40– 43) overrides class Commission. Employee’s To. String method (Fig. 10. 4, lines 60– 66) to return a String representation that’s appropriate for a Base. Plus. Commission. Employee. ◦ The derived class creates part of a Base. Plus. Commission. Employee object’s String representation by concatenating "base-plus-" with the String returned by calling Commission. Employee’s To. String method via the expression My. Base. To. String() (line 41). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 2 Creating Derived Class Base. Plus. Commission. Employee � Base. Plus. Commission. Employee’s To. String method then concatenates the remainder of a Base. Plus. Commission. Employee object’s String representation (that is, the value of class Base. Plus. Commission. Employee’s base salary) before returning the String. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 3 Testing Class Base. Plus. Commission. Employee � Figure 10. 6 tests class Base. Plus. Commission. Employee. � Lines 9– 10 create a Base. Plus. Commission. Employee object and pass "Bob", "Lewis", "333 -33 -3333", 5000, 0. 04 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 Base. Plus. Commission. Employee’s properties to output the object’s data. � Notice that we’re able to access all of the Public properties of classes Commission. Employee and Base. Plus. Commission. Employee here. � Lines 25– 26 calculate and display the Base. Plus. Commission. Employee’s earnings by calling its Caculate-Earnings method. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 3. 3 Testing Class Base. Plus. Commission. Employee � Because this method is called on a Base. Plus. Commission. Employee object, the derivedclass version of the method executes. � Next, lines 29– 31 modify the Gross. Sales, Commission. Rate and Base. Salary properties. � Lines 34– 36 output the updated data—this time by calling the Base. Plus. Commission. Employee’s To. String method. � Again, because this method is called on a Base. Plus. Commission. Employee object, the derived class version of the method executes. � Finally, lines 39– 40 calculate and display the Base. Plus. Commission. Employee’s updated earnings. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 My. Base 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 baseclass instance variables that are part of the derived-class object. � For example, let’s reconsider the Commission. Employee– Base. Plus. Commission. Employee hierarchy from Figs. 10. 4 and 10. 5. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 4 Constructors in Derived Classes � When a program creates a Base. Plus. Commission. Employee object (Fig. 10. 6, lines 9– 10), the Base. Plus. Commission. Employee constructor is called. � That constructor, before executing its full body code, immediately calls Commission. Employee’s constructor (Fig. 10. 5, line 14), which in turn calls Object’s constructor. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Commission. Employee (Fig. 10. 4, lines 15– 19) that are part of the Base. Plus. Commission. Employee object. � When the Commission. Employee’s constructor completes execution, it returns control to the Base. Plus. Commission. Employee’s constructor, which initializes the Base. Plus. Commission. Employee object’s base. Salary. Value (via property Base. Salary; Fig. 10. 5, line 15). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 baseclass 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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” derivedclass 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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, Space. Ship and La-ser. Beam. � Imagine that each class inherits from the common base class called Space. Object, 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 Space. Object array) of references to objects of the various classes. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Space. Ship object might draw itself as a bright silver flying saucer. � A Laser. Beam 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Space. Object and provides its own Draw method implementation. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 6 Introduction to Polymorphism: Polymorphic Video Game � When objects of class Mercurian appear in the Space. Object 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Change. Color. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Two. Dimensional. Shape. � Similarly, we could derive concrete classes Sphere, Cube and Tetrahedron from abstract base class Three. Dimensional. Shape. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Two. Dimensional. Shape, it knows that twodimensional 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 7 Abstract Classes and Methods � Declaring Abstract Classes and Abstract Methods ◦ You make a class abstract by declaring it with keyword Must. Inherit. ◦ An abstract class normally contains one or more abstract methods. ◦ An abstract method is declared with keyword Must. Override, as in Public Must. Override Sub Draw() ' abstract method © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 7 Abstract Classes and Methods � Must. Override methods do not provide implementations. � A class that contains any Must. Override methods must be declared as a Must. Inherit class even if it contains some concrete methods. � Each concrete derived class of a Must. Inherit base class must provide concrete implementations of all the base class’s Must. Override methods. � Constructors and Shared methods cannot be overridden, so they cannot be declared Must. Override. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8 Case Study: Payroll System Class Hierarchy Using Polymorphism � Let’s reexamine the Commission. Employee– Base. Plus. Commission. Employee 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Salaried. Employee and Commission. Employee. � Class Base. Plus. Commission. Employee 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Salaried. Employee, Commission. Employee, and the indirectly derived concrete class Base. Plus. Commission. Employee. � The last section shows a test program that builds objects of these classes and processes them polymorphically. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 First. Name, Last. Name and Social. Security. Number will appear in abstract base class Employee. � Class Employee also provides methods Calculate. Earnings and To. String. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 1 Abstract Base Class Employee � Method Calculate. Earnings certainly applies to all employees, but each specific earnings calculation depends on the employee’s class. � So we declare the method as Must. Override in base class Employee because a default implementation does not make sense for that method—there is not enough information to determine what amount Calculate. Earnings should return for a general Employee. � Each derived class Overrides Calculate. Earnings with an appropriate specific implementation. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 1 Abstract Base Class Employee � The program we build in Fig. 10. 13 iterates through an array of Employee variables and calls Calculate. Earnings for each Employee object. � These method calls are processed polymorphically. � Including the abstract method Calculate. Earnings in class Employee forces every directly derived concrete class of Employee to override Calculate. Earnings. � Method To. String in class Employee returns a String containing the first name, last name and social security number of the employee. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 1 Abstract Base Class Employee � Each derived class of Employee will override method To. String 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 Calculate. Earnings and To. String across the top. � For each class, the diagram shows the desired results of each method. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Must. Inherit class, meaning it can be used only as an abstract base class. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 To. String (lines 17– 20), which returns the String representation of an Employee ◦ Must. Override (abstract) method Calculate. Earnings (line 23), which must be implemented by concrete derived classes. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 1 Abstract Base Class Employee � Why did we decide to declare Calculate. Earnings as a Must. Override 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 Must. Override, we indicate that every concrete derived class must provide an appropriate Calculate. Earnings implementation that Overrides the base class method, and that a program will be able to use baseclass Employee variables to invoke method Calculate. Earnings polymorphically for every type of Employee. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 2 Concrete Derived Class Salaried. Employee (Fig. 10) inherits from class Employee (line 4) and overrides Calculate-Earnings (lines 33 – 35), which makes Salaried. Employee 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 Weekly. Salary property that has a Get accessor (lines 18– 20) to return weekly-Salary. Value’s value and a Set accessor (lines 22– 29) to assign a new nonnegative value to instance variable weekly. Salary. Value ◦ a method Calculate. Earnings (lines 33– 35) to calculate a Salaried. Employee’s earnings ◦ a method To. String (lines 38– 42) that returns a String including the employee’s type, namely, "salaried employee: ", followed by employeespecific information produced by base class Employee’s To. String method, and the value of Salaried-Employee’s Weekly. Salary property. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 2 Concrete Derived Class Salaried. Employee � Class Salaried. Employee’s constructor passes the first name, last name and social security number to base class Employee’s constructor (line 12). � Method Calculate. Earnings overrides abstract method Calculate. Earnings of Employee with a concrete implementation that returns the Salaried. Employee’s weekly salary. � Salaried. Employee’s To. String method (lines 38 – 42) overrides Employee method To. String. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 2 Concrete Derived Class Salaried. Employee � If class Salaried. Employee did not override To. String, the class would have inherited Employee’s To. String method. � In that case, Salaried. Employee’s To. String method would simply return the employee’s full name and social security number, which does not fully represent a Salaried. Employee. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 2 Concrete Derived Class Salaried. Employee � To produce a complete String representation of a Salaried. Employee, the derived class’s To. String method returns "salaried employee: " followed by the base-class Employeespecific information (that is, first name, last name and social security number) obtained by invoking the base class’s To. String 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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 3 Concrete Derived Class Commission. Employee (Fig. 10. 11) inherits from class Employee (line 4); therefore, Commission. Employee 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 gross. Sales. Value and commission. Rate. Value, respectively ◦ Set accessors (lines 24– 31 and 40– 47) that assign validated new values to these instance variables ◦ method Calculate. Earnings (lines 51– 53) to calculate a Commission. Employee’s earnings ◦ method To. String (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 Gross. Sales and Commission. Rate. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 3 Concrete Derived Class Commission. Employee � The Commission. Employee’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 To. String calls base-class method To. String (line 59) to obtain the Employee-specific information (that is, first name, last name and social security number). © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 4 Indirect Concrete Derived Class Base. Plus. Commission. Employee � Class Base. Plus. Commission. Employee (Fig. 10. 12) inherits class Commission. Employee (line 4) and therefore is an indirect derived class of class Employee. � Class Base. Plus. Commission. Employee 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 Commission. Employee constructor (line 14) to initialize the inherited members ◦ a property Base. Salary whose Set accessor (lines 24– 31) assigns a validated new value to instance variable base. Salary. Value, and whose Get accessor (lines 20– 22) returns base. Salary. Value © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 4 Indirect Concrete Derived Class Base. Plus. Commission. Employee ◦ method Calculate. Earnings (lines 35– 37) which calculates a Base. Plus. Commission. Employee’s earn-ings—line 36 calls base-class Commission. Employee’s Calculate-Earnings method to calculate the commission-based portion of the employee’s earnings (another nice example of code reuse) ◦ method To. String (lines 40– 43) which creates a String representation of a Base. Plus. Commission. Employee that contains "base-plus-", followed by the String obtained by invoking base-class Commission. Employee’s To. String method (another nice example of code reuse), then the base salary. � Recall that Commission. Employee’s To. String method calls Employee’s To. String method, so Base. Plus. Commission. Employee’s To. String initiates a chain of method calls that spans all three levels of the Employee hierarchy. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 5 Demonstrating Polymorphic Processing � To test our Employee hierarchy, the program in Fig. 10. 13 creates an object of each of the three concrete classes Salaried. Employee, Commission. Employee and Base. Plus. Commission. Employee. � 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 output. Text. Box 1. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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 Salaried. Employee is an Employee, a Commission. Employee is an Employee and a Base. Plus. Commission. Employee is an Employee. ◦ Therefore, we can assign the references of Salaried. Employee, Commission. Employee and Base. Plus. Commission. Employee objects to base-class Employee variables, even though Employee is a Must. Inherit (abstract) class. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 5 Demonstrating Polymorphic Processing � Polymorphically Processing Employees ◦ Lines 36– 41 iterate through array employees and invoke methods To. String (line 39) and Calculate. Earnings (line 40) with Employee variable current. Employee, which is assigned the reference to a different Employee in the array during each iteration. ◦ The output displayed- in output. Text. Box 2 illustrates that the appropriate methods for each class are indeed invoked— you can compare the results in output. Text. Box 2 with the non-polymorphic results in output. Text. Box 1 to see that they’re identical. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 8. 5 Demonstrating Polymorphic Processing � All calls to methods To. String and Calculate. Earnings are resolved polymorphically at execution time, based on the type of the object to which current. Employee refers. � This process is known as late binding. � For example, line 39 explicitly invokes method To. String of the object to which current. Employee refers. � As a result of late binding, the proper To. String method to call is decided at execution time rather than at compile time. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

© 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

10. 9 Online Case Study: Interfaces The book’s Companion Website (www. pearsonhighered. com/deitel) 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. � © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.

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. © 1992 -2011 by Pearson Education, Inc. All Rights Reserved.
- Slides: 116