Friday, February 1, 2013

The clearest way to express polymorphism


http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading/154939#154939
public abstract class Human
{
   ...
   public abstract void goPee();
}

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

public class Female extends Human
{
...
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 group = new ArrayList();
group.add(new Male());
group.add(new Female());
// ... add more...

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