Java Reference
In-Depth Information
their code to a specific implementation because a change in requirements for the next
iterationcouldresultinanewimplementation,andtheymightfindthemselvesrewriting
significant amounts of code, which wastes time and slows development.
Interfaceshelpyouachieveflexibilitybydecouplinginterfacefromimplementation.
fromclassesthatsubclassthe
Shape
class,andtheniteratesovertheseobjects,calling
eachobject's
draw()
method.Theonlyobjects thatcanbedrawnarethosethatsub-
class
Shape
.
Supposeyoualsohaveahierarchyofclassesthatmodelresistors,transistors,andoth-
erelectroniccomponents.Eachcomponenthasitsownsymbolthatallowsthecompon-
enttobeshowninaschematicdiagramofanelectroniccircuit.Perhapsyouwanttoadd
a drawing capability to each class that draws that component's symbol.
Youmightconsiderspecifying
Shape
asthesuperclassoftheelectroniccomponent
class hierarchy. However, electronic components are not shapes (although they have
shapes)soitmakesnosensetoplacetheseclassesinaclasshierarchyrootedin
Shape
.
However,youcanmakeeachcomponentclassimplementthe
Drawable
interface,
which lets you add expressions that instantiate these classes to the
drawables
array
This is legal because these instances are drawables.
Whereverpossible,youshouldstrivetospecifyinterfaces insteadofclassesinyour
code,tokeepyourcodeadaptabletochange.Thisisespeciallytruewhenworkingwith
For now, consider a simple example that consists of the Collections Framework's
java.util.List
interface, and its
java.util.ArrayList
and
java.util.LinkedList
implementationclasses.Thefollowingexamplepresents
inflexible code based on the
ArrayList
class:
ArrayList<String> arrayList = new ArrayList<String>();
void dump(ArrayList<String> arrayList)
{
// suitable code to dump out the arrayList
}
This example uses the generics-based parameterized type language feature (which I
stance. In this example,
String
objects are stored.