表达多态的最清晰的方法是通过抽象基类(或接口)。public abstract class Human{
...
public abstract void goPee();}
类是抽象的,因为goPee()方法不适用于人类。它只适用于男性和女性的子类。另外,人是一个抽象的概念-你不能创造一个既不是男性也不是女性的人。一定是其中之一。
因此,我们使用抽象类来推迟实现。public class Male extends Human{...
@Override
public void goPee(){
System.out.println("Stand Up");
}}
和public class Female extends Human{...
@Override
public void goPee(){
System.out.println("Sit Down");
}}
现在我们可以告诉一整间屋子的人去撒尿。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();}
运行此操作将产生以下结果:Stand UpSit Down...