多态 Polymorphism

多态就是指一个变量, 一个方法或者一个对象可以有不同的形式.

多态主要分为

  • 重载overloading
  1. 就是一个类里有两个或更多的函数,名字相同而他们的参数不同.
  • 覆写overriding
  1. 是发生在子类中!也就是说必须有继承的情况下才有覆盖发生. 当你继承父类的方法时, 如果你感到哪个方法不爽,功能要变,那就把那个函数在子类中重新实现一遍.

例子

重载 静态捆绑 (static binding) 是 Compile 时的多态

  1. EmployeeFactory.create(String firstName, String lastName){...}
  2. EmployeeFactory.create(Integer id, String lastName){...}

覆写 动态捆绑 (dynamic binding) 是 runtime 多态

  1. public class Animal {
  2. public void makeNoise()
  3. {
  4. System.out.println("Some sound");
  5. }
  6. }
  7. class Dog extends Animal{
  8. public void makeNoise()
  9. {
  10. System.out.println("Bark");
  11. }
  12. }
  13. class Cat extends Animal{
  14. public void makeNoise()
  15. {
  16. System.out.println("Meawoo");
  17. }
  18. }
  19. public class Demo
  20. {
  21. public static void main(String[] args) {
  22. Animal a1 = new Cat();
  23. a1.makeNoise(); //Prints Meowoo
  24. Animal a2 = new Dog();
  25. a2.makeNoise(); //Prints Bark
  26. }
  27. }