Converting Between Class and Interface Types
You can convert
from a class type to an interface type, provided
the class implements the interface
BankAccount account = new BankAccount(10000);
Measurable x = account; // OKCoin dime = new Coin(0.1, "dime");
Measurable x = dime; // Also OK
Cannot convert
between unrelated types
Measurable
x = new Rectangle(5, 10, 20, 30); // ERROR
Because Rectangle doesn't implement Measurable
Casts
Add coin objects to DataSet
DataSet coinData = new DataSet();
coinData.add(new Coin(0.25, "quarter"));
coinData.add(new Coin(0.1, "dime"));
. . .
Measurable max = coinData.getMaximum(); // Get the largest coin
What can you do with it? It's not of type Coin
String name = max.getName(); // ERROR
You need a cast to convert from an interface type to a class type
You know it's a coin, but the compiler doesn't. Apply a cast:
Coin maxCoin = (Coin) max;
String name = maxCoin.getName();
If you are wrong and max isn't a coin, the compiler throws an exception
Difference with
casting numbers:
When casting number types you agree to the information
loss
When casting object types you agree to that risk of causing an exception
Can you use a cast (BankAccount) x to convert a Measurable variable x to a BankAccount reference?
Answer: Only if x actually refers to a BankAccount object.
If both BankAccount and Coin implement the Measurable interface, can a Coin reference be converted to a BankAccount reference?
Answer:
No – a
Coin
reference can be converted to a
Measurable
reference,
but if you attempt to cast that reference to a
BankAccount,
an exception occurs.