Java Reference
In-Depth Information
Coin dime = new Coin(0.1, "dime");
Measurable x = dime;
// Also OK
Thus, when you have an object variable of type
Measurable
, you don't actually
know the exact type of the object to which
x
refers. All you know is that the object
has a
getMeasure
method.
However, you cannot convert between unrelated types:
Measurable x = new Rectangle(5, 10, 20, 30);
// Error
That assignment is an error, because the
Rectangle
class doesn't implement the
Measurable
interface.
Occasionally, it happens that you convert an object to an interface reference and you
need to convert it back. This happens in the
getMaximum
method of the
DataSet
class. The
DataSet
stores the object with the largest measure, as a
Measurable
reference.
DataSet coinData = new DataSet();
coinData.add(new Coin(0.25, "quarter"));
coinData.add(new Coin(0.1, "dime"));
coinData.add(new Coin(0.05, "nickel"));
Measurable max = coinData.getMaximum();
Now what can you do with the
max
reference? You know it refers to a
Coin
object,
but the compiler doesn't. For example, you cannot call the
getName
method:
String coinName = max.getName();
// Error
That call is an error, because the
Measurable
type has no
getName
method.
395
396
However, as long as you are absolutely sure that
max
refers to a
Coin
object, you
can use the cast notation to convert it back:
Coin maxCoin =
(Coin)
max;
String name = maxCoin.getName();
You need a cast to convert from an interface type to a class type.