Java Reference
In-Depth Information
no use for interfaces. Interfaces play into the far more important use of the type system, which
is to allow compile-time checking of the arguments and return values passed to and returned
from methods.
All methods in the Java language are defined by their name and by the types of their arguments
(the objects that are passed in to the method) and their return values (the object, if there is
one, that is handed back by the method). [ 7 ] If Foo , Bar , and Baz are all types defined in our
program, then we can define a method quux as:
Foo quux (Bar arg1, Baz arg2)
This tells us that the first argument passed in to the method quux must be of type Bar , the
second must be of type Baz , and the value returned will be an object (actually, a reference to
an object) of type Foo . Best of all, this is something that the compiler will enforce. If we try
to pass something other than a Bar into the method quux as the first argument, we will be told
that the object being passed in is not of the correct type, and the compiler will refuse to com-
pile the code. Further, if we have a method declared as:
Foo quux (Baz arg1, Bar arg2)
this will be seen as a different method than the one declared previously.
This makes the Java language type-safe; that is, it is impossible to pass (or return) an object of
the wrong type to a method. Those of us who use languages such as Java or C++ are so used
to this language feature that we tend to forget that there are many languages that have a type
system but are not type-safe. There are languages that use types only to size objects, and allow
anything to be sent into or returned from a method. Those languages allow great flexibility,
but also rely on the programmer to ensure that the right things are handed to these methods.
The Java compiler may trust, but it also verifies.
Why Have Three?
Having three different ways to define a type—classes, abstract classes, and interfaces—may
seem excessive to some. Indeed, I have seen lots of code that never uses the interface
keyword and does all of its work with classes and abstract classes. This was especially true in
the early days of Java, when there was more worry about the efficiency of the programs that
were written in the language. Declaring a type using an interface and then having that inter-
Search WWH ::

Custom Search