Java Reference
In-Depth Information
The
SwimmableTest
class uses the new type defined by the
Swimmable
interface in a number of ways. The purpose of
the class is just to demonstrate the use of an interface as a new type. It uses the
Swimmable
interface as a type to declare
iSwimmable
.
•
An instance variable named
aSwimmable
for its constructor.
•
A parameter named
getSwimmable()
method.
•
The return type of its
newSwimmable
for its
setSwimmable()
method.
•
A parameter named
localSwimmable
inside its
letItSwim()
method. Inside the method,
you could have invoked
swim()
method directly on the instance variable,
iSwimmable
. You
used a local variable just to demonstrate that an interface type can be used anywhere a type
can be used.
•
A local variable named
At this point, two questions about interfaces need to be answered.
•
What object in memory does a variable of an interface type refer to?
•
What can you do with a variable of an interface type?
Since an interface defines a reference type, what object in memory does a variable of an interface type refer
to? Let's expand on this question with an example. You have a
Swimmable
interface and you can declare a reference
variable of type
Swimmable
as follows:
Swimmable sw;
What is the value of the variable
sw
at this point? A variable of a reference data type refers to an object in memory.
To be precise, let's rephrase the question as “What object in memory does
sw
refer to?” You cannot answer this
question completely at this point. The partial and unexplained answer is that a variable of an interface type refers to
an object in memory whose class implements that interface. The answer will be clearer when I discuss implementing
an interface in the next section. You cannot create an object of an interface type. An interface is implicitly
abstract
and it does not have a constructor. That is, you cannot use an interface type with the
new
operator to create an object.
The following code would not compile:
Swimmable sw2 = new Swimmable(); // A compile-time error
In this statement, the use of the
new
operator causes the compile-time error, not the
Swimmable sw2
part.
The
Swimmable sw2
part is a variable declaration, which is valid.
However, one thing is certain: a variable of an interface type can refer to an object in memory. This scenario is
depicted in Figure
17-1
.
An object whose class
implements the
Swimmable interface
SW
Figure 17-1.
A Swimmable type variable (sw) referring to an object in memory