Java Reference
In-Depth Information
You need to be careful when casting because it is possible to fool the compiler with a cast
that fails at runtime. For example, suppose we have a class called Dog that also extends Pet :
public class Dog extends Pet {
public Dog(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println(“Dog is eating”);
}
}
Notice that the Dog class overrides eat from Pet . Study the following code carefully and
see if you can determine if it compiles and its result:
22. Pet one = new Dog(“Fido”, 2);
23. one.eat();
24. ((Dog) one).eat();
25. ((Cat) one).eat();
On line 23, the compiler sees the eat method of Pet , but at runtime the eat method in Dog
is invoked. Line 24 casts one to a Dog , which is valid and the eat method in Dog is invoked
again. Line 25 compiles because the Cat class inherits an eat method from Pet , so invoking
eat on a Cat is normally a valid statement and the code compiles fi ne. However, the one
reference does not point to a Cat object, and the JVM throws an exception at runtime, as
seen in the following output:
Dog is eating
Dog is eating
Exception in thread “main” java.lang.ClassCastException:
Dog cannot be cast to Cat
at PolymorphismDemo.main(PolymorphismDemo.java:25)
As you can see, we need to be careful when casting a reference “down the
inheritance tree” so that we are casting the reference to its appropriate type. To avoid a
ClassCastException , use the instanceof operator, discussed in the next section.
The instanceof Operator
The instanceof operator is a Boolean operator used to compare a reference to a class type.
If the reference is of the given class type, then the result is true ; otherwise, it's false . The
syntax for instanceof is
reference instanceof ClassName
Search WWH ::




Custom Search