Polymorphism
Polymorphism
POLYMORPHISM (RECAP)
Remember, Polymorphism means; the occurrence of
something in many different forms.
We have called the area method of the Shapes array objects,
and every time different version (form) of the area method
were called.
Moreover, we deal with objects of types Rectangle, Circle,
Triangle and Square in two different ways. One time we
consider them of the subclass type and another time as object
of superclass type
2
In particular, Polymorphism allow us to write programs that
process objects that share the same superclass in a class
hierarchy as if they are all objects of the same superclass.
So, Polymorphism allows to us to program in general rather
than in specific.
ENHANCED FOR LOOP
To iterate through all the objects of the array shapes we
can use the following code:
for(int i=0; i<shapes.lenght;i++)
System.out.println(shapes[i].area( ));
We can use the enhanced for loop to accomplish the
same effect
For(Shape s : shapes)
System.out.println(s.area( )); 2
we read the above statement: for each object s of type
Shape in the collection shapes
The general format for the Enhanced For:
For(Type variable : collection)
TYPICAL SCENARIO WHERE WE CAN USE
POLYMORPHISM
Consider as an example a video game that has a number of
objects each of which has a draw method to be drawn on the
screen.
Suppose also, that each of these object inherits from the same
superclass which contains the draw method.
we can have one array of all the objects and we can call the
draw method the same way for every object in the game, still,
every object has his own draw method. 2
Moreover, presenting new object types for the hierarchy
would require minimal changes to the code.
This style of programming is called Polymorphic
programming.
CASTING AND INSTANCEOF
Casting is the explicitly conversion from one type to another.
For example:
double x = 10.5; int
y = (int) x;
This is called explicit cast as we force the conversion of the
type double to be int.
The same thing can be done with object types Example:
Rectangle r1 = (Rectangle) shapes[0]; The above line of
code is only correct if the real type of the array object
shapes[0] is a Rectangle.
2
If the real type is something else, say for example Circle, that
would result in an exception (runtime error).
CASTING AND INSTANCEOF (CONT..)
We can check for the real type of the object using the
statement “instanceof”
Example:
If(shapes[0] instanceof Rectangle){
Rectangle rec1 = (Rectangle) shapes[0]; }
The if statement will only be true if object shapes[0] real
type is Rectangle.
Important: In the book “Java How to Program” take a
look at the example at page 469.
SUMMARY OF THE ALLOWED ASSIGNMENTS 2
BETWEEN SUPERCLASS AND SUPCLASS
VARIABLES