Title: Doubts about the use of polymorphism, and also about how is polymorphism related to casting?
Tags: java;oop;polymorphism;instanceof
Question: I give lessons on the fundamentals of the Java programming language, to students who study this subject in college.

Today one of them got me really confused with her question, so I told her to give me just a day to think about the problem, and I'll give her as accurate of an answer as I can.

She told me that the teacher got really angry when she used the keyword ```instanceof``` in her exam.

Also, she said that the teacher said that there is not a way to prove how polymorphism worked if she used that word.

I thought a lot to try to find a way to prove that in some occasions we need to use ```instanceof```, and also that even if we use it, there still some polymorphism in that approach.

So this is the 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) {
        //APPROACH 1
        makeItTalk(new Cat());
        makeItTalk(new Dog());
        makeItTalk(new Hippopotamus());

       //APPROACH 2
        makeItClimbToATree(new Cat());
        makeItClimbToATree(new Hippopotamus());
    }

    public static void makeItTalk(Animal animal) {
        animal.talk();
    }

   public static void makeItClimbToATree(Animal animal) {
       if(animal instanceof Cat) {
            ((Cat)animal).climbToATree();                  
       }
       else {
           System.err.println("That animal cannot climb to a tree");
        }
    }
}
```

My conclusions are the following:


The first approach (APPROACH 1) is a simple demo of how to program to an interface, not a realization. I think that the polymorphism is clearly visible, in the parameters of the method ```makeItTalk(Animal animal)```, and also in the way the method talk is called, by using the animal object.(This part is ok)
The second part is the one that makes me confused. She used ```instanceof``` at some point in her exam (I don't know how their exam looked like), and that was not accepted correctly because the teacher said, you are not proving 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 just in one of the implementing classes.

As you can see, only cats can climb to trees, and it would not be logical to make a Hippopotamus or a Dog climb to a tree. I think that could be an example of when to use ```instanceof```


But what about polymorphism in approach 2?
How many uses of polymorphism do you see there (only approach 2)?
Do you think this line has some type of polymorphism in it?

```((Cat)animal).climbToATree();``` 


I think it does, because in order to achieve a Casting of this type, the objects need to have an IS-A relationship, an in some way that is polymorphism.


What do you think, is it correct?
If yes, how would you explain with your own words, that casting relies on polymorphism?



Here is the accepted answer: In your above example, there is no need to call   

```makeItClimbToATree (new Hippopotamus ());
```

It could be easily avoided, if makeItClimbToATree wouldn't expect an animal, but something more specific, which is really able to climb a tree. The necessity to allow animals, and therefore to use instanceof, isn't visible. If you manage the animals in a List of animals, it will be more obvious. 

While ircmaxells explanation starts great, while introducing the Koala and other TreeClimbers, he doesn't see a second extension which is hiding in a sea anemone: different capabilities of animals like seaAnemoneHider, winterSleeping, blueEyed, bugEating, and so on, and so on. You would end up with boolean over boolean, constantly recompiling the base class, as well as breaking extending customer classes, which would need recompilation again, and wouldn't be able to introduce their own possibilities in a similar manner. 

Customer A would need Customer B to declare a NotBugEatingException, to get your behaviour into the base class. 

Introducing your own interfaces, combined with instanceof, is a much cleaner approach, and more flexible. Customer A might define divingLikeAPenguin and customer B trumpeting, both not knowing of each other, both not affecting the Animal class and not provoking useless recompilations. 

```import java.util.*;

interface Animal {
    public void talk ();
}

interface TreeClimbing {
    public void climbToATree ();
}

class Dog implements Animal {
    public void talk () { System.out.println("Woof!"); }
}

class Cat implements Animal, TreeClimbing {
    public void talk () { System.out.println("Meow!"); }    
    public void climbToATree () { System.out.println ("on top!"); }
}

public class TreeCriterion {

    public static void main(String[] args) {
        List <Animal&gt; animals = new ArrayList <Animal&gt; ();
        animals.add (new Cat ());
        animals.add (new Dog ());

        discuss (animals);
        upTheTree (animals);
    }

    public static void discuss (List <Animal&gt; animals) {
        for (Animal a : animals)
            a.talk ();
    }

    public static void upTheTree (List <Animal&gt; animals) {
        for (Animal a : animals) {
            if (a instanceof TreeClimbing)
                ((TreeClimbing) a).climbToATree ();
        }
    }
}
```

We don't need a third animal, dog and cat are enough. I made them default visible instead of public, to make the whole example fit into a single file. 

Comment for this answer: I still feel this type of strategy will lead to violations of the [SRP](http://en.wikipedia.org/wiki/Single_responsibility_principle) and [LSP](http://en.wikipedia.org/wiki/Liskov_substitution_principle) leading to huge classes and an unmaintainable ball of code.  Instead, I would either use a [Bridge](http://sourcemaking.com/design_patterns/bridge) or a [Visitor](http://sourcemaking.com/design_patterns/visitor) to decouple the walking/climbing implementation(s) from the animal class.  Otherwise you wind up with a boat load of interfaces and demi-god objects that do way too much...
Comment for this answer: This is a really good one. So here you use instanceOf with the Interface that is implemented by the animals that can climb. Great idea, i think it is a good approach and also Object Oriented. +1
Comment for this answer: @Michael I think i also agree with `user unknown`, imagine you have a class called Human, they can also climb to trees. So they need to implement that interface. I think this approach is in some way like creating marker interfaces. There is a similar thing already being done in java: The Serializable interface must be implemented by all those clases that wish to be serialized. I think it is correct and also flexible to work this way.
Comment for this answer: @user unknown: In that case, if you start adding more and more animals with a greater variety of abilities, developing a more dynamic approach would probably be better (as opposed to creating interfaces for each "ability group").  Something like creating a normal "Animal" class with a "List abilities" field.
Comment for this answer: Thanks. The code would be a bit clearer, but much longer, with more animals with multiple abilities, and multiple intersections. And multiple parties providing software to interact with each other. A base class provider for animal, who provides a management solution for a zoo for example, and specialists, for bears, for insects, for aquariums, where some customeer might not need any of the aquarium specific classes (because he has no aquarium), and some special aquarium doesn't need WinterSleeping or TreeClimbing.
Comment for this answer: Yes. And then? If you would like to call climbTree for every animal, which has this ability in its list? Would it just be a String? That would be easy, and very extensible, but not be checked by the compiler for spelling errors, and how would you move from knowing, that the BlackBear can climb the tree, to actually climbing it?
Comment for this answer: I don't have the climbing and so on in the animal class, but in the interfaces, which is the SRP, and in the concrete class (Cat). An interface MouseEating could be implemented by Cat and Eagle, TreeClimbing by Cat and Bear, Something else by Bear and Eagle (MoneyDecoration?). I don't see a LSP-violation, can you elaborate on this one?

Here is another answer: ```
  Do you think this line has some type of polymorphism in it?
```

```((Cat)animal).climbToATree();
```

No.  Especially, since ```Cat``` is a leaf class in the example.

```
  I think it does, because in order to achieve a Casting of this type, the objects need to have an IS-A relationship, an in some way that is polymorphism.
```

Polymorphism requires the IS-A relationship, but not the other way round.

Polymorphism is when you dispatch to (potentially) different methods based on an abstract interface.  If you don't have that dispatching, then it is not using polymorphism.  In your example, using ```instanceof``` to cast to a class with no subclasses, you are removing the need for dispatching.

(Of course, there is more than one way to "do polymorphism" in Java.  You can implement it using interfaces, using abstract classes, or using concrete classes with subclasses ... or hypothetical subclasses that may be written in the future.  Interfaces (and dispatching based on an interface) are generally the best way because they give a clean separation of the API from the identity of class.)

And on a separate note, using ```instanceof``` like that is typically a sign of poor design and / or poor modelling.  Specifically, it hard-wires the assumption that only cats can climb, which is trivially falsified if we include other animals into the model / program.  If that happens, your code breaks.

Comment for this answer: Thank you, for the explanation now i understand better why there is no polymorphism in that concrete line of code. Regarding to the instanceOf, i agree, maybe if i used it in a different way(for example the user's unknown approach above), could be better. Some of the answers mentioned that instanceOf is bad, i think that would be true, but only if you use it in a no flexible way, as i did.

Here is another answer: I'm surprised no one wrote anything about Late Binding. Polymorphism in Java = Late Binding. The method being called will be be attached to the object when we finally know its type. In your example:

``` if(animal instanceof Cat) {
     ((Cat)animal).climbToATree();                  
 }
```

You are calling ```climbToATree()``` on a Cat object so the compiler accepts it. At run time, there is no need to check the type of the calling object since ```climbToATree()``` belongs to ```Cat``` only. And so there is no polymorphism in these lines of code.

About casting being related to Polymorphism, it isn't. Casting just limits the fields that are shared in both objects, if the cast is legal. You could do this:

```class A {
    int getInt() {}
}

class B extends A {
    int getInt() {}
}

// in main
A a = new B();
A b = (A)a;
b.getInt(); // This would still call class B's getInt();
```

The cast itself added no value, getInt() was bound at run time to the runtime type of ```a```, which was class B.


Here is another answer: What about something like the code below? It solves the generality problem by separating the tree-climbing as another interface you can implement or not on your animals. It fits the problem better: climbing trees is not an intrinsic property of all animals, only of a subset of them. At least to me it looks much clearer and elegant than throwing ```NotImplementedException```s.

```
public interface Animal {
    public void talk();
}

public interface AnimalCanClimbTrees extends Animal {
    public void climbToATree();
}

public class Dog implements Animal {
    public void talk() {
        System.out.println("Woof!");
    }
}
/* Animal is probably not needed, but being explicit is never bad */
public class Cat implements Animal, AnimalCanClimbTrees 
{
    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) {
       //APPROACH 1
       makeItTalk(new Cat());
       makeItTalk(new Dog());
       makeItTalk(new Hippopotamus());

       //APPROACH 2
       makeItClimbToATree(new Cat());
       makeItClimbToATree(new Hippopotamus());
   }

   public static void makeItTalk(Animal animal) {
       animal.talk();
   }

   public static void makeItClimbToATree(Animal animal) {
       if(animal instanceof AnimalCanClimbTrees) {
           ((AnimalCanClimbTrees)animal).climbToATree();                  
       }
       else {
           System.err.println("That animal cannot climb to a tree");
       }
   }
}
```

Comment for this answer: Yeah, I remembered that just now before your reply. Wrote a little comment on it.
Comment for this answer: @Chris Dennett: That was my original name, then I noticed it doesn't make explicit the fact that a climber is still an animal. `AnimalTreeClimber` sounds a little weird, so I went with 'AnimalCanClimbTrees'.
Comment for this answer: That is nice, just one little mistake. Cat only needs to implement AnimalCanClimbTrees, because that interface already extends from animal. Thanks :)
Comment for this answer: `makeItClimbToATree` shouldn't accept Animals, but only TreeClimbers.
Comment for this answer: TreeClimber would be better as an interface name.
Comment for this answer: Okay, but if there's any confusion, the package name (relating to animals) can be used to differentiate the interface :)

Here is another answer: The ```instanceof``` operator has nothing to do with polymorphism.  It is simply used to see whether or not an object is an instance of a particular class.  You see this operator being used a lot in the ```equals()``` method, because the method takes a generic ```Object``` as a parameter:

```public class Cat implements Animal{
  @Override
  public boolean equals(Object obj){
    if (obj == null || !obj instanceof Cat){
      //obj is null or not a "Cat", so can't be equal
      return false;
    }
    if (this == obj){
      //it's the same instance so it must be equal
      return true;
    }
    Cat catObj = (Cat)obj; //cast to "Cat"
    return this.getName().equals(catObj.getName()); //compare the two objects
  }
}
```

If a class does not implement a method, then it should throw an exception.  I believe the "official" exception you are supposed to throw is ```UnsupportedOperationException```.  To be "correct", I think the ```Animal``` interface should have a ```public void climbToATree();``` method.  The ```climbToATree()``` methods in the ```Dog``` and ```Hippo``` classes should throw an ```UnsupportedOperationException``` because they cannot implement this method.  But if you are throwing this exception very often, then there may be something wrong with your object model, as this is not a common thing to do I don't think.

Also note that it's helpful (but not required) to use the ```@Override``` annotation with polymorphic programming in Java.  This will cause a compilation error to be thrown if a method with this annotation does not override a parent method, implement an abstract method, or (in Java 6) implement an interface method.  This can help catch any mistakes you make in the method signature.  For example:

```public String tostring(){
  return "foobar";
}
```

Without the annotation, the program would compile and run successfully.  But this was not your intention!  You wanted to override toString(), but you accidentally spelled the name wrong!!

Comment for this answer: I understand, thank you for your answer. Regarding to polymorphism and casting, how to you think are those topics related to each other?

Here is another answer: The reason the ```instanceof``` method is seen as bad is simple.  Cats aren't the only ```Animal``` that might be able to climb a tree.

What happens if down the road you need to add a Koala class.  Then your simple ```if``` becomes a not so simple ```or```.  Then, what happens when you add another class?  and another one.  And another one.  That's the prime reason why ```instanceof``` is seen as bad.  Because it couples the implementation to a concrete class, rather than opening it for the callee to determine what to do.

Simply implement the ```makeItClimbToATree()``` method to throw a ```CantClimbTreesException``` if called on an animal that can't climb.  That way you have the best of both worlds.  Easy to implement, and easy to extend.

IMHO, ```instanceof``` has only 1 truly valid use: In a test case to test the returned instance from a method matches the expected return type (in non-type safe languages).

Basically any other use can more than likely be refactored away or designed differently to negate the need for its use.

Another way to look at it is this: Polymorphism allows you to eliminate almost all conditional statements from your code.  The only conditionals that you can't get rid of (at least all of them) are in object creational methods (such as in a factory where it must choose the class based upon a runtime argument).  Just about any other conditional can be replaced by polymorphism.  Therefore, anything that does conditional execution is by definition anti-polymorphic.  That's not to say it's bad (there's a huge difference between Good and Good Enough),  But in an academic discussion, it's not polymorphic...

Never forget the 60/60 rule.  60% of your total development time will be spent maintaining the code you wrote, and 60% of that time will be spent adding new features.  Make maintaining easier, and your life will be easier as well.  That's why ```instanceof``` is bad.  It makes the initial design easier, but complicates the long term maintenance (which is more expensive anyway)...

Comment for this answer: @sfrj: There is and there is not polymorphism there.  There is in the sense that any *child* of `Cat` can be treated the same.  But in the sense of this discussion (Since you're typehinting against `Animal`, it should work on all children of animals, not just one subtree), no there is not.
Comment for this answer: @sfrj: Yes, but if that was the case, the `instanceof` method would be polymorphic as well.  The only difference is that the cast will throw an exception on failure rather than return a boolean.  You *could* do it that way, but it just feels wrong to me...
Comment for this answer: @user: I would argue that all of that functionality would not belong on the base class in the first place.  You'd wind up with a huge ball of code that will be impossible to maintain.  I'd go as far as arguing that if your interface has more than 4 or 5 methods, it's prob a good candidate for refactoring.  So my full answer to your objection would be to break out that functionality into another class tree separate from the animal.  But I didn't say that because that's outside the scope and spirit of this particular question.  I hope that clarifies it a bit...
Comment for this answer: This was a really good practical explanation. Thank you.Can i ask you just one more thing i am interested: What do you think about the line where the casting is being done. Do you think, is there any type of polymorphism there?
Comment for this answer: @ircmaxell I understand partially, i am confused in one thing: I thought that all the IS-A relationships(implementation and inheritance), are in some way polymorphic, so always when do type casting, polymorphism is being proved. Is that i just said correct?
Comment for this answer: @ircmaxell You are right, it looks wrong to me too. My goal was to try to find and argument to help her earn maybe a couple of points at the exam review. Thank you very much for your help clearing my doubts.
Comment for this answer: The first part of your explanation is excellent, but when you suggest to use Exceptions, it is nearly as worse. Some animals will hide in a sea anemone, some will sleep in winter, some will do this, and some will do that. You will end up adding booleans over booleans to the base class, and checks and checks into the subclasses. Instead, using different interfaces for different capabilities will only affect classes which really use this features, and allow a much more loose coupling.

Here is another answer: Maybe I'm missing the point and don't get the context of the exam question, but whether an ```Animal``` can climb a tree should be a part of the class that implements ```Animal```.  For example, if ```Animal``` is an interface, you could have a method ```boolean isCapableOfClimbing()``` and then each implementing class would be able to indicate its capability.

A method that attempted to make the animal climb could then use that. It doesn't make sense for a method that's trying to make the animal climb a tree check whether it's an instance of a particular class, since then that method is specifying something that should be specified in the implementing class. A simple method should not provide behaviour for a class that it's using.

As for your question of when to use ```instanceof```, once place where it will almost always be used is if overriding the ```equals()``` method of a class, since it only accepts an ```Object``` and you typically have to ensure it is of the same type so it can be cast and then meaningfully compared.

Comment for this answer: @rick: Yes.  The problem is the contrived example; if you're ever in a situation where you have a generic `Animal`, you shouldn't be prepared to ask it to `climb` (for a start, what class would `climb` be a method on?).
Comment for this answer: Wouldn't `isCapableOfClimbing()` break the 'Tell, Don't Ask?' mantra?
Comment for this answer: @Oli - probably an interface `Climber` and `Climbable` interface as objects to be climbed upon. I agree that `Animal` is too broad to have any `climbing` or `talking` methods, not all animals are capable of producing a sound or climbing. Maybe `Mammal` interface with `GiveBirth` or `BreastFeed` will be more appropriate as an example.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 8, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2011:00:06/03/11', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<java><oop><polymorphism><instanceof>', 'Title': 'Doubts about the use of polymorphism, and also about how is polymorphism related to casting?', 'ViewCount': 960, 'id': 6233731, 'user_AboutMe': '<p>Enthusiastic java developer based in London, I love stackoverflow, I use it regularly for many years and is a great way of helping and ask for help. Also i love blogging about software.</p>\n<p>Please visit my Blogs:</p>\n<ul>\n<li><a href="https://javing-uk.medium.com" rel="nofollow noreferrer"><strong>Javing (Medium)</strong></a></li>\n<li><a href="http://www.javing.blogspot.com" rel="nofollow noreferrer"><strong>Javing (Blogger)</strong></a></li>\n</ul>\n', 'user_AccountId': 304562.0, 'user_DisplayName': 'javing', 'user_Reputation': 11947.0, 'user_Views': 3341.0, 'user_id': 614141.0}}