What Is Abstraction In Object-Oriented Programming?
This is a quick blog post on my understanding of abstraction. Abstraction is one of the key concepts of object-oriented programming.
It’s main purpose is to hide details, and only expose a high-level mechanism for using it. Implementation details should not be shown.
An example of abstraction, is an abstract class. An abstract class can contain abstract methods. This means a class extending from the abstract class, needs to implement the abstract methods. It isn’t concerned with how it is done, as long as the abstract methods are implemented.
I have a blog post on abstract classes, and interfaces here, but here’s a quick example, using an abstract class Phone and a concrete class, MobilePhone:
1public abstract class Phone {2 public abstract void acceptIncomingCall();3 public abstract void makeOutgoingCall();4 public abstract void ring();5}67public class MobilePhone extends Phone {8 public void acceptIncomingCall(){9 if(isRinging() & isPickupCallButtonPressed()){10 answerCall();11 }12 }1314 public void makeOutgoingCall(){15 if(!isRinging() & isPhoneNumberEntered()){16 makeCall();17 }18 }1920 public void ring(){21 System.out.println("Ring!");22 }2324*// note: other **private **methods in MobilePhone are not shown - isRinging(), isPickupCallButtonPressed(), isPhoneNumberEntered(), answerCall(), methodCall()*25}
As demonstrated, MobilePhone has implemented the abstract methods from Phone.
Another demonstration of abstraction is shown in MobilePhone
, where only the public methods, acceptIncomingCall()
, makeOutgoingCall
, and ring()
are exposed to other classes (public).
All the other stuff under the hood is hidden and the following methods are private: isRinging(), isPickupCallButtonPressed(), isPhoneNumberEntered(), answerCall(), methodCall()
.
Discussion