I give lessons in the basics of the Java programming language for students studying this subject in college.
Today one of them made me embarrass her question, so I told her to give me only one day to think about the problem, and I will give her the most accurate answer as soon as I can.
She told me that the teacher was very angry when she used the instanceof keyword in her exam.
In addition, she said that the teacher said that there is no way to prove how polymorphism worked if she used the word.
I thought a lot to try to find a way to prove that in some cases we need to use instanceof , and also that even if we use it, there is still some polymorphism in this approach.
So, here is an example I made:
public interface Animal { public void talk(); } class Dog implements Animal { public void talk() { System.out.println("Woof!"); } } public class Cat implements Animal { public void talk() { System.out.println("Meow!"); } public void climbToATree() { System.out.println("Hop, the cat just cimbed to the tree"); } } class Hippopotamus implements Animal { public void talk() { System.out.println("Roar!"); } } public class Main { public static void main(String[] args) {
My findings are as follows:
The first approach (APPROACH 1) is a simple demonstration of how to program an interface, not an implementation. I think that polymorphism is clearly visible in the parameters of the makeItTalk(Animal animal) method, as well as in the name of the method call using the animal object. (This part is fine)
The second part bothers me. She used instanceof at some point in her exam (I don’t know what their exam looked like), and it was mistaken because the teacher said that you did not prove polymorphism.
To help her understand when she can use instanceof , I thought about telling her that she can use it when the method she needs to call is not in the interface, but it is in only one of the implementation classes.
As you can see, only cats can climb trees, and it would be illogical to get a hippo or dog to climb a tree. I think this might be an example of when instanceof should be used.
But what about polymorphism in approach 2?
How many applications of polymorphism do you see there (only approach 2)?
Do you think that there is some kind of polymorphism in this line?
((Cat)animal).climbToATree();
I think this is so, because in order to achieve Casting of this type, objects must have an IS-A relationship, in some ways this is polymorphism.
Do you think this is right?
If so, how would you explain in your own words that casting is dependent on polymorphism?