In the book, it says: " if(x instanceof Dog) ((Dog)x).bark();
The if statement checks to see if the object x belongs to the class Dog before casting x to a Dog. Its important to use instanceof before a downcast when you dont have other information that tells you the type of the object; otherwise, youll end up with a ClassCastException."
I don't understand this: concerning the 'if' sentence, if x was 'instanceof' Dog, there's no need to downcast at all; on the other hand, when x was not (which would happen, if x was some instance of the class that Dog is actually inherited from, i.e. at the time exactly downcast would be needed), then the so-called 'downcast' here wouldn't be performed.
What's the sense of this short graph of program and the following comments?
You have as parameter an Object obj and in case it is an instance of class Dog you want to call one method in class Dog. You can do this in 2 ways: obj.getClass().getName().equals().... but is difficult and the other solution is if (obj instanceof Dog) { Dog aDog = (Dog)obj; aDog.aMethod(); }
If you don' perform the downcast you cannot access the method "aMethod" which belongs to Dog.