Lesson Sunday

Abstraction is one of the most important concepts in object-oriented programming. Abstraction is the process of hiding complex code so that it's easier to use. Encapsulation (via access modifiers) is the tool we use to achieve abstraction. Because this concept is literally quite abstract and can be a bit difficult to grasp, let's look at an example.

When we drive a car, we only need to know a few things about the car. These things can be boiled down to a set of methods such as .Start(), .Steer(), .Stop() and .Go(). We don't need to know how these methods work behind the scenes in order to use them. Many things happen in a car's engine when we .Start() the car but they are quite complex and we'd rather concern ourselves with other matters.

In other words, we could say the underlying complexity of the car's engine has been abstracted away to just a handful of methods which are easy to understand.

In computer programming, we encapsulate the complexity of our code in methods.

public class Car
  public void Start()
    // A lot of complex stuff is happening in here but we don't need to understand it or even know about it in order to .Start() a car. In fact, this method might need to call a dozen other methods, but we wouldn't want the user to have to call them all manually!

Now our method can be called outside the class:

Car yugo = new Car("1980 Yugo Koral", 700, 56000)

We don't see any information about how the .Start() method is achieved. Nor do we need to know anything about a Car's private methods and fields in order for .Start() to work.

We are already using abstraction regularly every time we write a well-encapsulated method that can be used outside a class. In fact, we can think of abstraction as being an important payoff of encapsulation.


Abstraction: The process of hiding and encapsulating complex code so that it's easier to use.

Lesson 2 of 12
Last updated more than 3 months ago.