Polymorphism vs Inheritance

后端 未结 6 1525
青春惊慌失措
青春惊慌失措 2021-02-01 20:23

Suppose I have two classes: Animal and Dog. Dog is a subclass of Animal. I do the following code:

Animal a = new Dog();

Now I can call methods

6条回答
  •  甜味超标
    2021-02-01 20:58

    Polymorphism allows you to write a method that works for any Animal:

    public void pet(Animal animal) {
       ...
    }
    

    This method would accept Dog, Cat, etc, including subclasses of Animal that are yet to be written.

    If the method were to take Dog, it would not work for Cat etc.

提交回复
热议问题