Java Reference
In-Depth Information
{
double X = 2.0;
}
interface C extends A, B
{
}
differentreturntypesandinitializers.However,ifyouimplement
C
andthentrytoac-
Listing 2-48.
Discovering a name collision
class Collision implements C
{
public void output()
{
System.out.println(
X
); // Which X is accessed?
}
}
Supposeyouintroducea
void foo();
methodheaderdeclarationintointerface
A
,
andan
int foo();
methodheaderdeclarationintointerface
B
.Thistime,thecom-
piler will report an error when you attempt to compile the modified
Listing 2-47
.
Why Use Interfaces?
Now that the mechanics of declaring, implementing, and extending interfaces are out
of the way, we can focus on the rationale for using them. Unfortunately, newcomers
toJava'sinterfacesfeatureareoftentoldthatthisfeaturewascreatedasaworkaround
toJava'slack ofsupportformultiple implementation inheritance. While interfaces are
useful in this capacity, this is not their reason for existence. Instead,
Java's
i
nterfaces
feature was created to give developers the utmost flexibility in designing their applic-
ations, by decoupling interface from implementation. You should always code to the
interface.
Those who are adherents to
agile software development
(a group of software devel-
opment methodologies based on iterative development that emphasizes keeping code
simple,testingfrequently,anddeliveringfunctionalpiecesoftheapplicationassoonas
theyaredeliverable)knowtheimportanceofflexiblecoding.Theycannotaffordtotie