Java Reference
In-Depth Information
When defining a constant in an interface, you can (and should) omit the keywords
public static final
, because all fields in an interface are automatically
public static final
. For example,
public interface SwingConstants
{
int NORTH = 1;
int NORTHEAST = 2;
int EAST = 3;
. . .
}
394
395
9.2 Converting Between Class and Interface Types
Interfaces are used to express the commonality between classes. In this section, we
discuss when it is legal to convert between class and interface types.
Have a close look at the call
bankData.add(new BankAccount(10000));
from the test program of the preceding section. Here we pass an object of type
BankAccount
to the
add
method of the
DataSet
class. However, that method
has a parameter of type
Measurable
:
public void add(
Measurable
x)
Is it legal to convert from the
BankAccount
type to the
Measurable
type?
You can convert from a class type to an interface type, provided the class
implements the interface.
In Java, such a type conversion is legal. You can convert from a class type to the type
of any interface that the class implements. For example,
BankAccount account = new BankAccount(10000);
Measurable x = account;
// OK
Alternatively,
x
can refer to a
Coin
object, provided the
Coin
class has been
modified to implement the
Measurable
interface.