What is the difference between Abstraction and Polymorphism

后端 未结 11 718
挽巷
挽巷 2021-01-30 07:09

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:26

    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.

    0 讨论(0)
  • 2021-01-30 07:26

    The confusion regarding the actual meaning of abstraction in the context of object orientation is comprehensible: it adds little, if something, to the concepts of inheritance, encapsulation and even polymorphism. If you master these three concepts, there is no need to concern too much with "abstraction" once it is naturally embedded in them (particularly inheritance).

    To start with, note that the term "abstraction" has multiple meanings and it is not incorrect to state, e.g., that encapsulation requires abstraction: when you use access modifiers to protect the attributes of a class while exposing the methods that handle them (that's what encapsulation is), the class' user no longer needs to worry how to handle them by herself. So, in a sense, when you design a class, you abstract by properly encapsulating methods and attributes - everything the class' user needs to do is use it by invoking the right methods, and this is a form of abstraction.

    Furthermore, if you think straight, polymorphism is also a form of abstraction: your code calls a method provided by some class and you have no idea how it is gonna act until that actual class type is determined (at runtime). So, it is correct to state that the polymorphic behavior is a kind of abstraction.

    However, when used as a standalone term to describe the characteristics of OOP, abstraction must be understood as the proper representation of the system under discussion in the form of a suitable class hierarchy. As such, abstraction is the result of the designer's mental processes that culminate in an appropriate design for the classes that are gonna be used in a program. To quote an (excellent!) post that can be found at the javarevisited blog:

    ... Abstraction hides details at the design level, while Encapsulation hides details at the implementation level.

    While the above statement is correct, I find the "hides details" part misstated - I would rephrase it as something like

    Abstraction concerns with design details, deciding how the class hierarchy should look like, Encapsulation hides details implementation.

    To be fair with the author, this very idea is put beautifully along his article. The term "abstraction" with this connotation is also seen in good books like Head First Object-Oriented Analysis and Design, and I quote a statement from there:

    Whenever you find common behavior in two or more places, look to abstract that behavior into a class, and then reuse that behavior in the common classes

    Notice the usage of abstraction here: "look to abstract that behavior into a class". Now, if to abstract means to design a class hierarchy properly as suggested above, abstraction could be defined as the representation of a domain by using classes conveniently, taking advantage of the concepts of inheritance and encapsulation.

    In the particular case of Java, abstraction is implemented by using interfaces and abstract classes while encapsulation is implemented with the private, protected and package access modifiers.

    0 讨论(0)
  • Abstraction and Polymorphism are similar in nature with a different purpose.

    For ex.

    A driving license: you are given a license mentioning the class of vehicles you are allowed to drive. The license mentions the class of vehicle allowed by the authority but it doesn't define or mention which specific car or brand you should drive. This is Abstraction.

    here License is an Abstract class and its method, the allowed vehicles is its Abstract method.

    Now, here, Polymorphism is different ways individual License is alloted by the authority to different people, some are issued for light vehicles while some for heavy and some are given for commercial vehicles, according to different requirement. Here, License is a base class, and other kinds of licenses are its child classes, also obeying the is-a relationship. Commercial License is a License.

    So, Abstraction is a general guideline giving independence of implementation to the follower classes while Polymorphism is differential approach which override the methods/rules set by parent class.

    0 讨论(0)
  • 2021-01-30 07:31

    These two are among the most important characteristics of Object Oriented paradigm.

    Abstraction.

    Object orientation models the software as real world objects. However it would be too hard ( and useless ) to model ALL the properties a Customer may have, or all the properties an Employee have.

    By listing only the interesting attributes of an object OO may use effectively that object for an specific domain. That's abstraction.

    For instance an Employee in a HR system may have very different attributes than a Online BookStore. We abstract the details to make is useful.

    Polymorphism.

    Objects may behave differently depending on the "type" while keeping the same interface.

    What does this means?

    For instance an online store system may have two sub-classes of Employee

    A) Internal employees.

    B) Contractors

    And a method to calculate the discount for internal purchases

    The discount of an internal employee is calculated as: 10% + 2% for each worked year in the company + 2% for each.. mmhh child

    The discount of a contractor is 10%

    The following code to calculate the amount to pay:

     public Amount getAmountToPay( Product product, Employee internalCustomer ) { 
          Amount amount = product.getPrice();
          amount.applyDiscount( internalCustomer.getDiscount() );
          return amount;
     }
    

    Would produce different results for the two different kinds of Employee 's

    class Employee { 
        public int getDiscount();
    }
    
    
    class InternalEmployee extends Employee { 
         public int getDiscount() { 
            return 10 + 2 * getWorkedYears() + 2 * getNumberOfChilds();
         }
     }
    
     class Contractor extends Employee { 
          public int getDiscount() { 
              return 10;
         }
     }
    

    This is the polymorphism in action. Instead of having something like

     Amount amount = product.getPrice();
    
     if( employee.isContractor() ) { 
          amount.applyDiscount( 10 );
     } else if( employee.isSomthingElse() ) {
          amount.applyDiscount( 10 * 2 * getYrs() + 2 * getChilds() );
     } else if ( employee.contidions, condigions, conditions ) {
          amount.applyDiscount( getSomeStrageRuleHere() );
     }
    

    We let the runtime to choose which one to calculate. Is like the program behaves differently depending on the type:

          Amount amount = product.getPrice();
          amount.applyDiscount( internalCustomer.getDiscount() );
          return amount;
    

    By the way, in this example the "Amount" is an abstraction of a real life concept, that could also be represented as a double or an Integer, but maybe we have interestion methods inside that would be better if set in its own class.

    I hope this helps.

    0 讨论(0)
  • 2021-01-30 07:42

    Both terms are used heavily in object oriented programming, but they are not specifically limited to that context.

    Abstraction is a generalization of something else; a step higher in perspective. A heirarchy for instance can be seen as an abstraction on the organizational structure of a company. Generally it is used in the context of what things are underneath (such as their base types). The point of abstracting is to write less code that is more general in nature, so that you can run it for a larger set of problems. A spreadsheet for example is an abstraction that allows for a specific type of information storage. More?

    Polymorphism is also a generalization, but one that occurs in a runtime context. A bunch of different object types are polymorphic if there is some way to access them where they are indistinguishable from each other. That is, all of the objects look and feel the same, even if they are not. The purpose of this is to significantly reduce code; you can write one generalized solution to save from writing all of the different permutations for each different type. If you write a graphics library, you'd rather just write some abstract code to handle 'shapes', then have to write code for each different type, such as circles, squares, etc.

    These are both terms that are centered around properties in the code that will enable the programmers to do more with less. Less code has less bugs, is more stable and is easier to maintain. The alternative is to use "brute force" to pound out millions and million of lines of very specific (and very fragile) code. More code is harder to fix, and much harder to keep up-to-date.

    Paul.

    0 讨论(0)
  • 2021-01-30 07:42

    very easy.

    1. Abstraction is abstraction. Class 'Student' is an abstraction of a real student.

    2. Polymorphism is when one class represents another so that user won't notice. This could happen when classes implement the same interface or one class derives from another. Class 'HighSchoolStudent' is derived from class 'Student'. When class 'Teacher' calls #attendance method on the object it might not know whether this object is of 'Student' class or 'HighSchoolStudent' class.

    0 讨论(0)
提交回复
热议问题