Java Reference
In-Depth Information
class, which happened by default. Since an object of the Fish class has two types, Fish and Swimmable , you can assign
the reference of a Fish object to a variable of the Fish type as well as to a variable of the Swimmable type. The following
code summarizes this:
Fish guppi = new Fish("Guppi");
Swimmable hilda = new Fish("Hilda");
The variable guppi is of the Fish type. It is referring to the Guppi fish object. There is no surprise in the first
assignment; a Fish object being assigned to a variable of the Fish type. The second assignment is also valid because
the Fish class implements the Swimmable interface and every object of the Fish class is also of the Swimmable type. At
this point hilda is a variable of the Swimmable type. It is referring to the Hilda fish object. The following assignment is
always valid:
// A Fish is always Swimmable
hilda = guppi;
However, the other way is not valid. Assigning a variable of the Swimmable type to a variable of the Fish type
generates a compile-time error.
// A Swimmable is not always a Fish
guppi = hilda; // A compile-time error
Why does the above assignment generate a compile-time error? The reason is very simple. An object of the Fish
class is always Swimmable because the Fish class implements the Swimmable interface. Since a variable of the Fish type
can only refer to a Fish object, which is always Swimmable , the assignment hilda = guppi is always valid. However, a
variable of the Swimmable type can refer to any object whose class implements the Swimmable interface, not necessarily
only to a Fish object. For example, consider a class Turtle , which implements the Swimmable interface.
public class Turtle implements Swimmable {
public void swim() {
System.out.println("Turtle can swim too!");
}
}
You can assign an object of the Turtle class to hilda variable.
hilda = new Turtle(); // OK. A Turtle is always Swimmable
If the assignment guppi = hilda is allowed at this point, a Fish variable guppi will be referring to a Turtle
object! This would be a disaster. The Java runtime would throw an exception, even if the compiler had allowed this
assignment. This kind of assignment is not allowed for the following reason:
A Fish is always Swimmable. However, not every Swimmable is a Fish.
Suppose you know (programmatically) for sure that a variable of the Swimmable type contains reference to a Fish
object. If you want to assign the Swimmable type variable to a variable of the Fish type, you can do so by using a type
cast, as shown:
// The compiler will pass it. The runtime may throw a ClassCastException.
guppi = (Fish)hilda;
Search WWH ::




Custom Search