Polymorphism vs Inheritance

后端 未结 6 1439
青春惊慌失措
青春惊慌失措 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 21:02

    In Java, the concepts of polymorphism and inheritance are "welded together"; in general, it does not have to be that way:

    • Polymorphism lets you call methods of a class without knowing the exact type of the class
    • Inheritance lets derived classes share interfaces and code of their base classes

    There are languages where inheritance is decoupled from polymorphism:

    • In C++ you can inherit a class without producing polymorphic behavior (i.e. do not mark functions in the base class with virtual)
    • In Objective C you can implement a method on an unrelated class, and call it from a place that knows only the signature of the method.

    Going back to Java, the reason to use polymorphism is decoupling your code from the details of the implementation of its counter-parties: for example, if you can write a method Feed(Animal animal) that works for all sorts of animals, the method would remain applicable when you add more subclasses or implementations of the Animal. This is in contrast to a Feed(Dog dog) method, that would be tightly coupled to dogs.

    As far as the

    Dog d = new Dog();
    

    declaration goes, there is no general reason to avoid this if you know that the rest of your method deals specifically with dogs. However, in many cases the later is not the case: for example, your class or your methods would often be insensitive to the exact implementation, for example

    List numbers = new ArrayList();
    

    In cases like that, you can replace new ArrayList() with new LinkedList(), and know that your code is going to compile. In contrast, had your numbers list been declared as ArrayList numbers, such switchover may not have been a certainty.

    This is called "programming to an interface". There is a very good answer on Stack Overflow explaining it.

提交回复
热议问题