Java Reference
In-Depth Information
If you are wrong, and the object doesn't actually refer to a coin, your program will
throw an exception and terminate.
This cast notation is the same notation that you saw in Chapter 4 to convert between
number types. For example, if x is a floating-point number, then (int) x is the
integer part of the number. The intent is similarȌto convert from one type to another.
However, there is one big difference between casting of number types and casting of
class types. When casting number types, you lose information, and you use the cast to
tell the compiler that you agree to the information loss. When casting object types, on
the other hand, you take a risk of causing an exception, and you tell the compiler that
you agree to that risk.
S ELF C HECK
3. Can you use a cast (BankAccount) x to convert a Measurable
variable x to a BankAccount reference?
4. If both BankAccount and Coin implement the Measurable
interface, can a Coin reference be converted to a BankAccount
reference?
C OMMON E RROR 9.2: Trying to Instantiate an Interface
You can define variables whose type is an interface, for example:
Measurable x;
However, you can never construct an interface:
Measurable x = new Measurable(); // Error
Interfaces aren't classes. There are no objects whose types are interfaces. If an
interface variable refers to an object, then the object must belong to some classȌa
class that implements the interface:
Measurable x = new BankAccount(); // OK
Search WWH ::




Custom Search