8

I am reading the SCJP book by Kathy Sierra. I find Polymorphism a little confusing.

Could you please help me out with a real world example for the following?

I understand that Polymorphism only works when you have overridden methods, no matter if you do it via class or interface, and at run-time the JVM determines the method based on the Object type.

Lets say Horse extends from Animal and it also overrides the eat() method. What is the benefit of doing: Animal a = new Horse(); a.eat(); over Horse b = new Horse(); b.eat();?

Eventually the result is going to be the same. I apologize its a very basic question but even all the senior developers in my team gave me all different answers.

6
  • 3
    That's the usual terrible example that doesn't show why polymorphism is interesting, and instead makes it seem pointless :( Why anyone thinks this helps understand it, I don't know. Commented Mar 31, 2011 at 18:44
  • 1
    Just a small tip: Stop reading that book. It's a good book, but only if you want to get a java certificate. This is not a book for OOP beginners. Commented Mar 31, 2011 at 18:45
  • 1
    See the answer I posted here: stackoverflow.com/questions/5423125/… for a really thorough example of a real-world problem it solves. Commented Mar 31, 2011 at 18:47
  • Thanks J T. @Bv202, so that book is not good for learning? Commented Mar 31, 2011 at 18:51
  • 1
    I assume you're reading this book: amazon.com/Certified-Programmer-Study-310-055-Certification/dp/… If so, no, this is not a good book for OOP starters. You may want to read "Head First Java", a beginners book written by the same author. Commented Mar 31, 2011 at 18:53

7 Answers 7

15

To extend your example, say you have a farm of animals. Then a collection of all animals could be defined as

List<Animal> animals = new ArrayList<Animals>();
animals.add(new Horse());
animals.add(new Cow());
animals.add(new Sheep());

Then you could iterate over all the animals and have them all eat by

for(Animal a: animals) {
    a.eat();
}

Also they're essential for Design Patterns. I recommend you read about them @ http://en.wikipedia.org/wiki/Design_pattern_(computer_science)

Sign up to request clarification or add additional context in comments.

4 Comments

I will always update before post an answer, I will always update before post an answer, I will always update before post an answer...
Nice example Kurru. Thanks. How does it work in collections when we say: Map<String> myMap = new HashMap<String>;
@t0mcat: in the case with generics, you can only have the inheritance as you specified. However, you could still add subtypes of string to that collection. ie. myMap.put(new AwesomeString()) would be fine. The issue can be found in detail at en.wikipedia.org/wiki/…
@DJClayworth : iterate oops. Always misspell that
6

Imagine you have class Animal and three implementations : Horse, Cow and a Pig. And then you have a field where they are walking. So, you can make the following:

List<Animal> animals = new ArrayList<Animal>(3);
animals.add(new Horse());
animals.add(new Cow());
animals.add(new Pig());

for (Animal animal : animals) {
  animal.eat();
}

So here in the cycle you don't mind what concreate animal do you have: it can be a pig, or a cow, or the full list can be filled with just horses. But they are all animals, and they all can eat. Polymorphism is great here, because independent of what animal do you have, the method eat will be chosen in dependcy of the concreate object.

Comments

3

Lets say you have a farm.

List<Animal> farm = new ArrayList<Animal>();
farm.add(new Horse());
farm.add(new Pig());
farm.add(new Chicken());

Now lets make them all eat.

for(Animal animal : farm){
    animal.eat();
}

Comments

2

If you just have one subclass you can't explicitly see the advantages, but suppose you have also a second one called Lion:

public abstract class Animal {
   public abstract void eat;
}

public class Horse extends Animal {

   public void eat() {
      System.out.println("Eats gras");
   }

}

public class Lion extends Animal {

   public void eat() {
      System.out.println("Eats meat");
   }

}

And now you have a list of animals you can just do this and it will print to correct eat:

List<Animal> animals = new List<Animal>();
animals.add(new Lion());
animals.add(new Horse());

for(Animal a: animals) {
    a.eat();
}

Comments

2

Easy...

Imagine you've got several classes extending animal (like horse, dog, cat, duck) and put all your animal-objects into a List, then you can feed them all in one go by

for (Animal a: animalList) {
    a.eat();
}

and the're all fed without the need to find out, what kind of animal needs to be fed. O.K. your Animal-extending classes would have to make sure, that they eat the right stuff, but that's the point.

Comments

0

Polymorphism is about objects that share a base but do different things. For example, imagine creating a Chess program. It would be really nice if you could manage a collection of Pieces. You don't need to know that the pieces are pawns, knights, king, queen, etc... You only need to know certain things about the piece. The piece could have methods for determining its point value, determining what spaces are valid for it to move given a board of other pieces, etc...

You could make a tetris game as well. As you add new pieces from the top of the screen, it makes code much more reusable to treat all pieces the same but have different behaviors (rotation a block and rotation a line are very different).

Hopefully this helps you see the practicality. I realize these are only game examples, but I think they illustrate the point well.

Comments

0

In Animal a = new Horse(); a.eat() case a cannot call a Horse specific method where as in Horse b = new Horse(); b.eat(); b can call.

Horse specific means the method in horse but not in animal.

As a is a reference of Animal it doesnt know the methods declared in horse which are specific to Horse.

And more over a code like Animal a = new Horse(); will not be of that significance as you are statically assigning the instance. Polymorphism is more useful in cases where you dont know which subclass instance you will have in runtime.

3 Comments

Really? You are saying a cannot call Horse specific eat?
until you call as (Horse)a.horseSpcificmethod().
sorry a can call eat. but it cannot call a method which is there in horse not in animal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.