表达多态性的最清晰方式是通过抽象基类(或接口)
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 和 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.
因此,我们通过使用抽象类来推迟实现.
public class Male extends Human{
...
@Override
public void goPee(){
System.out.println("St和 Up");
}
}
和
public class Female extends Human{
...
@Override
public void goPee(){
System.out.println("Sit Down");
}
}
现在我们可以告诉一整间屋子的人go 小便.
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();
}
运行此命令将产生以下结果:
St和 Up
Sit Down
...