DEV Community

Discussion on: Explain Encapsulation and Polymorphism Like I'm Five

carlosmgspires profile image
Carlos Pires • Edited on

Abstraction:

Joey's Mom: "Joey, what do you want for breakfast?"
Joey: "I dunno, Mommy... I feel like something sweet and crunchy."
(Abstract class SweetAndCrunchy)

Joey's Mom: "Do you want granola with maple syrup?"
(GranolaMapleSyrup implements SweetAndCrunchy)

-- Edit --

As Dinesh Patra noticed, technically, this should be either:
(Abstract class SweetAndCrunchy)
(GranolaMapleSyrup extends SweetAndCrunchy)

or:

(Interface SweetAndCrunchy)
(GranolaMapleSyrup implements SweetAndCrunchy)

I would like to focus here on the Interface version.
"Abstraction" is a concept. The concept of abstraction in OOP is accomplished at several levels. The topmost level of abstraction is the Interface. An Interface declares one or more methods that should be implemented by the classes that implement that interface.
The next level of abstraction is the Abstract Class. This type of class can't be instantiated: it has to be extended by a concrete (normal) class. The problem with using abstract classes in the current discussion is that an abstract class can in fact already provide an implementation, which makes matters all the more confusing for people trying to learn OOP, so here I would like to stick to the concept of abstraction and forget about specifics.

Thread Thread
dance2die profile image
Sung M. Kim

Ace! Thanks Carlos 😄

Thread Thread
dineshpatra profile image
Dinesh Patra

Thanks Carlos. But I got a doubt.
As per my understanding, We can implement on interface and inherit from abstract classes right. So SweetAndCrunchy is an interface not abstract class.
Please correct me if my understanding is wrong.

Thread Thread
carlosmgspires profile image
Carlos Pires

Yes, you are right: the "implements" implies SweetAndCrunchy is an Interface.
But we were talking about the concept of abstraction, versus the concept of encapsulation.
"Abstraction" means you are talking about the idea of a thing, and not the concrete thing itself. "Encapsulation" means you can't change the inner workings of the thing.

Abstraction is accomplished at several levels. An Interface is the most abstract level of abstraction there is. To keep it simple, I wouldn't go now into abstract classes because those have very specific technicalities.

Thread Thread
dineshpatra profile image
Dinesh Patra

Thank you for the clarity explanation.