overlying theme:
don't use instaneof in place of plymorphism
(assuming previous definitions for classes Bathroom, Kitchen, and Lounge
and also for array Rooms of Objects as defined in article.)
an example of instanceof destroying polymorphism
(in a method to display size of each room)
if(rooms[i] instanceof Lounge)
size = ((Lounge) rooms[i]).getSize();
else if (similar code for Kitchen)
else if (similar code for Bathroom)
problem could instead be resolved be an abstract mthod ina a user defined
superclass. the method would them either be inhereted or overrriden and
polymorphism can be utilized.
for (int i=0;i< rooms.length, ++i)
System.out.println("Room " +(i+1)+ " is " + room.getSize();
hence the static type of an elemtne of array room is the superclass, and
the dynamic type is one of the sublcasses.
polymorphism:
an object of a superlcass can take ont he from of an object ofone of its
subclasses (a superclass refernce can be used to refer to an instance of
one of its subclasses)
essential type of polymorphic objects are known implicitly. (no type
checking is necessary - type dynamically resolved)
an object whose true type is hidden behind the facade of a superclass
importance:
permits greater extensibility and mroe complete ecapsulation (no need to
alter current calsses for new ones)
prevents programmer from "doing all the work"
by using method overrriding.
discuss briefly the 2nd example of articly dealing with mehod overriding
where problematice method doesn't belong to superclass (solution: making
superclass define one mthod sublcasses inheret or override. calling
method then uses superclass instead of dealing with each subclass.)
discuss briefly 1.0AWT where polymorphism isnt supported (event.target is
type Object thereby preventing polymorphism.) also situation when dynamic
type is needed, but no action is to be performed on it (counting number of
Bathrooms example)
more specific summary of theme:
instaceof shouldnt be used where it appears as a precursur to a
downcasting operation.