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