Java Reference
In-Depth Information
ing and dynamic binding meant that developers had enough structure to let the compiler
catch problems right away, but still had enough freedom to implement and use polymorph-
ism. Polymorphism lets developers override methods from superclasses and change their
behavior in subclasses, making reuse by inheritance practical. Even better, Java is dynam-
ically bound by default, so you can override anything you want unless the keyword final
is applied to a method.
Static typing makes Integrated Development Environments useful too, because they can
use the types to prompt developers for the correct fields and methods. IDEs like Eclipse
and NetBeans, both powerful and free, became pervasive in the industry partly as a result
of this convenience.
So what's wrong with static typing? If you want an earful ask any Smalltalk developer.
More practically, under Java's dynamic binding restrictions (that you can't override any-
thing unless two classes are related by inheritance), static typing is overly restrictive. Dy-
namically typed languages have much more freedom to let one object stand in for another.
As a simple example, consider arrays and strings. Both are data structures that collect in-
formation: arrays collect objects, and strings collect characters. Both have the concept of
appending a new element to the existing structure. Say we have a class that includes an ar-
ray and we want to test the class's methods. We're not interested in testing the behavior of
arrays. We know they work. But our class has a dependency on the array.
What we need is some kind of mock object to represent the array during testing. If we have
a language with dynamic typing, and all we are invoking is the append method on it using
character arguments, we can supply a string wherever we have an array and everything will
still work.
In Java one object can only stand in for another if the two classes are related by inheritance
orifbothimplement thesameinterface.Astaticreferencecanonlybeassignedtoanobject
of that type or one of its subclasses, or a class that implements that interface if the reference
is of interface type. In a dynamically typed language, however, we can have any classes
stand in for another, as long as they implement the methods we need. In the dynamic world
this is known as duck typing : if it walks like a duck and it quacks like a duck, it's a duck.
See figure 1.2 .
Search WWH ::




Custom Search