Sei sulla pagina 1di 15

Lecture 11: Polymorphism

Outline
 In the last lecture, we continued our discussion of Objects…
 Creating and Using Constructors:
 Used to create object instances with differing characteristics.
 Example: JTrain (cont.)
 Inheritance
 Which we used to create ‘Derived Classes’...
 Which inherit the characteristics of a Base Class
 Example: The JFreightTrain Class
 Overriding Base Class Constructors

 This lecture, we continue our discussion of Overriding…


 With Polymorphism, a simple but powerful concept
 Form 1 : Overriding Base Class Methods and Properties.
 Form 2 : The Ability of Methods to Accept ‘Related’ Classes.
 This will be illustrated with a generalized Multiple-JTrain Example…
 That uses both ‘forms’ of Polymorphism (this and next lecture).
 We will also learn the basics of creating our own custom Collections:
 Similar to Collections.ArrayList, but defined by us…
 By inheriting from the .NET System Class, CollectionBase.
Polymorphism
 It is often useful to re-define base-class Methods or Properties…
 So that many forms exist for the same basic behavior.
 This is called polymorphism = Multiple (poly-) + Form (-morph) + ism
 For instance, consider the Base Class, ‘Animal’.
 And 2 Derived Classes: Cat and Wolf.
 All Animals sleep, but the derived classes may sleep for different times.
 Defining different ‘Sleep’ methods for each provides ‘polymorphism’.

 Here, we discuss two types of Inheritance-based Polymorphism:


 Overriding Base Class Methods
 We saw this already, with Constructors…
 Polymorphism at Method Interfaces
 The ability of Methods to deal with ‘Related’ Objects ‘at the Interface’:
 Parameters and Return Value Types
Polymorphism and Overriding
 Basic Inheritance-based Polymorphism is provided by Overriding:
 First, a Method is defined in a Base Class.
 That Method is then re-defined (overridden) in a Derived Class…
 So that the Base and Derived methods exhibit different behaviors.

 A client of the Method (and Object) does not have to realize this.
 The Method may the be called more-or-less freely…
 Without knowing which Class (Base or Derived) an instance belongs to.
 Or even that several different behaviors have been defined.
 The behavior defined for each specific type will simply occur, automatically.

 This is important for encapsulation :


 ‘Unnecessary’ object details can be hidden from object clients, for simplicity !

 We already considered an example of overriding last lecture…


 A special-case example involves Constructors:
 We defined Class-specific Constructors for our derived class: JFreightTrain.
 No additional keywords were required.
Overriding (cont.)
 We may also override Base Class Methods other than New()…
 Example: The JTrain’s GetStatus() Method:
 Currently reports only Passenger Car Number.
 But: users might want information about Wagon Number, as well.
 So, let’s override the method for JFreightTrain!

 This more general type of overriding requires several steps:


1. You must declare that the Base Class Method is Overridable.
 Of course, the Method must be implemented by the Base Class.
2. The ‘Overrides’ keyword must then be used in the new Method’s definition.
 i.e., in the Derived Class.

 Example: Let’s change the GetStatus() Method of JFreightTrain…


 So that it also reports the number of Wagons (not only Cars).
 But first, let’s talk about Visibility.
The Issue of Accessibility
 In VB .NET, each element is defined to have a set ‘Visibility’:
 In other words, limits are defined on the accessibility:
 Of a Variable, Member, or Property for reading, or being written to;
 Of Procedures (Methods) for use.
 Again, this is important for compartmentalization and data hiding.
 Visibility levels available in VB.NET include:
 Public (*):
 Accessible within the Current Project, or in Other Projects that reference it.
 Friend (*):
 Accessible from within the Current Project, but not from outside projects.
 Protected:
 May be accessed within the same Class, or Derived Classes.
 Usable only within Classes (in fact, it will be useful to us, here).
 Private (*):
 May only be accessed within the same Module, Class, or Structure.
 Private is the default visibility.

 * Useable within Modules, Structures, or Classes, but not Procedures.


Example:
Polymorphism and Procedures
 Polymorphism also applies to behavior at Procedure ‘Interfaces’:
 If a Method accepts/passes an instance of a Base Class as a Parameter…
 It can also accept/pass an Instance of any Derived Class Instance, instead.
 This is a simple example of polymorphism at an ‘Interface’.
 Ex: A Method defined to accept a JTrain can also accept a JFreightTrain.
 Since everything a JTrain can do, a JFreightTrain can also do.

 There are a couple of limitations on this:


 This doesn’t work backwards…
 A Method defined to accept a Derived Class can’t accept the Base Class.
 Ex: A Method in Module1 which accepts a JFreightTrain can’t accept a JTrain.
 Common-sense must also prevail.
 If you try to call a behavior specific to a Derived Class inside the Method…
 You will get an error, even though the parameter pass would be successful.
 Why? The behavior may not be defined for the Base Class.
 One work-around: Provide a consistent interface at the Base Class.
 Make sure it provides minimal implementations of all ‘derived’ Methods:
 At least an ‘Empty’ Method for each Method implemented by a derived Class.
 Ex: Define an empty ‘AddWagon()’ for JTrain, that does nothing.
Collections.CollectionBase
 Back in Course 1, we learned about creating two types of lists:
1. Array : A basic, indexed list of elements.
 All elements must be the same primitive type…
 Supported Methods provide very basic list functionality.
2. ArrayList : An Object-based indexed list.
 With elements that could be quite general (not all the same type).
 Provided Methods: Add(), Remove(), and Find()
 These did a lot of ‘housekeeping’ for us, along the way ( resizing, etc. )
 ArrayList is actually: System.Collection.ArrayList

 When working with a list, it is best to define your own Collection…


 This is a Special purpose ‘list’ (kind of like ArrayList)…
 that Inherits from System.Collections.CollectionBase
 Creating your new Collection is very simple:
 First, define the new Collection as a Class inheriting from CollectionBase
 This Collection contains an inherited List that can be manipulated…
 To act on the List, you must define the following 3 resources:
 Add( x ) – This method appends item x to the Collection’s List
 Remove( i ) – This Method deletes the item at index i from the List
 Find( i ) – This Property gets the item at index i in the List
Example: The trains Collection
 Our Goal will be to Generalize our JTrain Project:
 We will define and use our own Collection called trains:
 Which can contain either JTrain or JFreightTrain Elements…
 So that we can add, remove, and command many trains at once.

1. We will need to add several new Procedures to Module1:


 AddTrain()
 Which Adds a new Train to trains
 FindTrain (String name)
 Which finds a train called name in trains
 CommandTrain (String name)
 Which allows the user to command a train in trains called ‘name’.
 For this, we will use the Select Case command structure we already have…
 All should work with either JTrain or JFreightTrain (polymorphism!)
 For this, we must add 2 empty Wagon Methods to JTrain.

2. We will also need to update the Main() method of Module1…


 To allow us to use all of these Procedures with trains.
 For this, we will define some new Commands.
 Finally, we will test functionality!
Trains Example: Some Preliminaries
The JTrainCollection Class
The CommandTrain() Method
The AddTrain() Method
Overview / Forward
 In this lecture, we have continued our discussion of
Objects…
 With Polymorphism, a simple but powerful concept
 Form 1 : Overriding Base Class Methods and Properties.
 Form 2 : The Ability of Methods to Accept ‘Related’ Classes.

 We also started to create our own custom


Collection:
 Similar to Collections.ArrayList, but defined by us…
 By inheriting from the .NET System Class, CollectionBase.

 Next Lecture:
 We will finish our ArrayList…
 And illustrate, with a generalized Multiple-JTrain Example.
 And combine our JTrain Classes
 into a new Class Library called ‘TrainsLib’.

Potrebbero piacerti anche