<< Chapter < Page | Chapter >> Page > |
The general rule
The type of the reference determines the names of the methods that can be called on the object. The actual type of the object determines which ofpossibly several methods having the same name will be executed.
Selection at runtime
Therefore, it is possible (at runtime) to select among a family of overridden methods and determine which method to execute based on the type ofthe subclass object pointed to by the superclass-type reference when the overridden method is called on the superclass-type reference.
Runtime polymorphism
In some situations, it is possible to identify and call an overridden method at runtime that cannot be identified at compile time. In those situations,the identification of the required method cannot be made until the program is actually running. This is often referred to as late binding , dynamic binding , or run-time polymorphism .
Project file structure
Figure 1 shows the project file structure for the Flex project named Polymorph02 .
The image in Figure 1 was captured from the Flex Navigator panel of Flex Builder 3.
Program output at startup
Figure 2 shows the program output at startup.
The program GUI
As you can see, the program GUI consists of a label, a button and an empty text area. Each time the user clicks the button, an object isinstantiated, and information about that object (similar to the information shown in Figure 3) is displayed in the text area.
Program class definitions
This program defines the following four classes as shown in the folder named CustomClasses in Figure 1:
As the name implies, the Driver class is the driver for the entire program. For example, it creates the GUI shown in Figure 2 at startup andupdates the GUI each time the user clicks the GO button as shown in Figure 3.
The classes named MyCircle and MyRectangle each extend the class named MyShape . Therefore, specialized shape objects can be instantiated from these two classes.
The class named MyShape defines an instance method named area , which returns the text shown in Figure 3 each time it is executed.
Sample output from area method of a MyCircle object
The class named MyCircle overrides the inherited area method to return a text string similar to that shown in Figure 4 each time it is executed.
The radius is a random value
Note, however, that the value of radius is established from a random number generator each time an object of the MyCircle class is instantiated, so the actual values for Radius and Area in Figure 4 will change each time the button is clicked.
Sample output from area method of a MyRectangle object
The class named MyRectangle also overrides the inherited area method to return a text string similar to that shown in Figure 5 each time it is executed.
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with actionscript' conversation and receive update notifications?