Polymorphism vs Overriding vs Overloading

Brian G picture Brian G · Sep 30, 2008 · Viewed 266.4k times · Source

In terms of Java, when someone asks:

what is polymorphism?

Would overloading or overriding be an acceptable answer?

I think there is a bit more to it than that.

IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?

I think overloading is not the right answer for sure.

Answer

Chris Cudmore picture Chris Cudmore · Sep 30, 2008

The clearest way to express polymorphism is via an abstract base class (or interface)

public abstract class Human{
   ...
   public abstract void goPee();
}

This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other.

So we defer the implementation by using the abstract class.

public class Male extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Stand Up");
    }
}

and

public class Female extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Sit Down");
    }
}

Now we can tell an entire room full of Humans to go pee.

public static void main(String[] args){
    ArrayList<Human> group = new ArrayList<Human>();
    group.add(new Male());
    group.add(new Female());
    // ... add more...

    // tell the class to take a pee break
    for (Human person : group) person.goPee();
}

Running this would yield:

Stand Up
Sit Down
...