Difference between Encapsulation and Abstraction

后端 未结 15 1138
萌比男神i
萌比男神i 2020-12-07 07:21

I had an interview today. I had a question from OOP, about the difference between Encapsulation & Abstraction?

15条回答
  •  爱一瞬间的悲伤
    2020-12-07 07:59

    Abstraction

    In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.

    Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.

    Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.

    Encapsulation:

    Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.

    1. If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
    2. Within a package, if we declare each class filed (member field) as private and having a public method to access those fields, this way giving class level encapsulation to those fields

提交回复
热议问题