Private Methods

Learn why and how to make methods private.

Remember that instance variables store data private to the object. Instance variables are only made accessible to the outside world (exposed) if we add attribute accessors to the class.

In the same way, classes sometimes want to keep certain methods private. These are methods that aren’t supposed to be called from outside of the object. Only the object itself is supposed to use them internally by calling them from its own other methods.

Imagine an instance of an ItalianRestaurant class with a pizza method, which is supposed to return an instance of the Pizza class.

When we call the pizza method (ask for a pizza), it should know what to do and how to do it. Dough will be prepared, sauce and vegetables and other such things will be gathered, and the pizza will be baked and served.

We don’t really care about these details, though. We’re hungry and just want a pizza. The exact steps involved are kept private, and perhaps they’ve been the family’s best-kept secret for generations.

This is essentially how objects work too! The ItalianRestaurant object exposes some stuff to the outer world (us) and keeps other things private. They’ll let us order a pizza and other things. But they won’t tell us the exact ingredients of their tomato sauce, or how they managed to make this great pizza dough.

Making a method private

In our Person example, it makes sense to make the encrypt method private.

Currently, if we run the following code, it executes just fine, even though it makes little sense:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy