What is the difference between Abstraction and Polymorphism

后端 未结 11 657
别那么骄傲
别那么骄傲 2021-01-30 07:17

I seem to not understand two OOP concepts very well. Could you explain what abstraction and polymorphism are, preferably with real examples and

11条回答
  •  [愿得一人]
    2021-01-30 07:50

    Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes.

    One example of a software abstraction is Java's Object.equals(Object o) method. You know that it will compare this object to the one passed in as a parameter, but you don't know, nor do you need to know, exactly how it will be implemented (unless you are the implementer of the class).

    Polymorphism means the ability to take more than one form. A method might have different behaviors in different instances. The behavior depends on the data types used in the operation.

    One of the classic examples of polymorphism uses an inheritance tree rooted in the Animal class. All Animal's have a makeNoise() method, but the Dog class and the Cat class implement it differently. This allows you to refer to any Dog's and Cat's using an Animal reference type.

    Animal a = new Dog();
    Animal b = new Cat();
    

    Now you can call makeNoise() on either Animal instance and know that it will make the appropriate noise. This is particularly useful if you have a Collection of Animals, and you don't know at run time exactly what type each of them really is.

提交回复
热议问题