Difference between Encapsulation and Abstraction

后端 未结 15 1118
萌比男神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 08:06

    Just a few more points to make thing clear,

    One must not confuse data abstraction and the abstract class. They are different.

    Generally we say abstract class or method is to basically hide something. But no.. That is wrong. What is the word abstract means ? Google search says the English word abstraction means

    "Existing in thought or as an idea but not having a physical or concrete existence."

    And thats right in case of abstract class too. It is not hiding the content of the method but the method's content is already empty (not having a physical or concrete existence) but it determines how a method should be (existing in thought or as an idea) or a method should be in the calss.

    So when do you actually use abstract methods ?

    • When a method from base class will differ in each child class that extends it.
    • And so you want to make sure the child class have this function implemented.
    • This also ensures that method, to have compulsory signature like, it must have n number of parameters.

    So about abstract class! - An Abstract class cannot be instantiated only extended! But why ?

    • A class with abstract method must be prevented from creating its own instance because the abstract methods in it, are not having any meaningful implementation.
    • You can even make a class abstract, if for some reason you find that it is meaning less to have a instance of your that class.

    An Abstract class help us avoid creating new instance of it!

    An abstract method in a class forces the child class to implement that function for sure with the provided signature!

提交回复
热议问题