Public, Private and Protected - Encapsulate Your Code Today!

Public, Private and Protected - Encapsulate Your Code Today!

Encapsulation, What Is It and When To Use It?

Introduction 🚀

Encapsulation is the process of using access modifiers (public, private and protected) to limit what variables or methods an object can access/call. Through your programming journey, if you've dabbled in Object-Oriented-Programming (OOP), then you will have seen at least one access modifier. If you're not sure what they are (or you wish to brush up your knowledge of them), then keep reading.

Public 🌳

Public is probably the first access modifier that you've seen. It's the quickest and easiest to explain, so I'll start with it.

If a variable or method within a class is set to public, then an instance of that class (an object) will be able to call that method or read the value of that variable. Let's say you have a calculator class with an "add" method:

class Calculator {
    public add(int num1, int num2) {
        return num1+num2;
    }
}

With the "public" access modifier, an object of the Calculator class will be able to call the "add" method:

Calculator calculator = new Calculator();
result = calculator.add(1,3);

System.out.println(result); // prints out 4

The same applies to variables; if a variable is set to public, then you'll be able to access the variable from an object of the class with "objectName.variable"

Private 🤫

Setting a method/variable to public isn't the best practice; in a project with many developers (or even just 1), it can be tricky to keep track of what variables objects shouldn't change (or have access to). This is where the private access modifier comes in.

The private access modifier stops objects from accessing variables or calling methods from the class. This means that if we were to take the Calculator example from the public section and change the "public" to "private", then it won't work since the "calculator" object won't be able to call the "add" method.

"private" only stops objects of the class from accessing/calling variables/methods, you'll still be able to access/call variables/methods inside of the class (so you'll be able to call the add method from another method in the Calculator class)

The private access modifier comes in handy when you want an object to access or call specific variables/methods, but not others or you want a variable to be viewable but not changeable. This is where "getters and setters" come in.

Getters and Setters

Getters are methods that return the value of a variable, and setters change the value of a variable based on the parameter passed in when calling. These come in handy if you want an object to be able to read the value of a variable, but not change it (or vice versa).

Let's say you're developing some piece of software that tracks users. In that software, you want to be able to read the username, but not change it, and you want to be able to change the password, but not view it. Your class may resemble the following:

class User {
    private String username;
    private String password;

    // Constructor for the class
    User(String username, String password) {
        this.username = username;
        this.password = password
    }

    // Getter for username
    public getUsername() {
        return username;
    }

    // Setter for password
    public setPassword(String newPassword) {
        password = newPassword;
    }
}

Notice how the getter and the setter are set to public. This is because we want an instance of the User class to be able to call them.

Now objects of the class are able to get the username by calling getUsername(), and they're able to set the password by calling setPassword(...) which would look something like the following:

User user = new User("Bob", "SuperSecretPassword!");

String usersUsername = user.getUsername();
System.out.println(usersUsername); // Prints out "Bob"

// Changes the password to "HelloWorld123"
user.setPassword("HelloWorld123");

It's worth noting that the variables "username" and "password" are set to private, this means that:

User user = new User("Bob", "SuperSecretPassword!");

String usersUsername = user.username;
String usersPassword = user.password;

Won't work, (it'll throw an error).

Protected 🛡

Protected is similar to private as it does the exact same thing, the only difference is that subclasses inherit protected variables but not private ones. This is known as inheritance.

Inheritance 👩➡👦

If you aren't familiar, inheritance is the practice of writing variables and/or methods in a class, and having similar classes "inherit" those variables/methods. Let's say you have a Car and Motorbike class, in them, you have a drive() method. Instead of writing the method twice, you could make a "parent/superclass" (let's call it Vehicle) and write the drive method in that class and have the Car + Motorbike classes inherit the method (meaning they can call it as if it were written in the Car/Motorbike class).

So instead of writing:

class Car {
     public drive() {...}
}

class Motorbike {
     public drive() {...}
}

You can make a parent/superclass called "Vehicle" (any name works) and write the class there:

class Vehicle {
     protected drive() {...}
}

and change the Car and Motorbike classes to:

class Car extends Vehicle {}
class Motorbike extends Vehicle {}

The extends keyword is what tells the program that it wants to inherit protected variables from a specific class, it changes between languages - in Java, it's "extends ClassName" (remember to change the ClassName to the class' name).

Now objects of the Car and Motorbike classes are able to call drive() like it was written into the class itself:

Car car = new Car();
Motorbike motorbike = new Motorbike();

car.drive();
motorbike.drive();

Note how the drive() method in the Vehicle class is protected. If it were anything else, this would not work as the drive() method would not have been inherited.

Conclusion

In short:

  • With public, an object can access or call any variable/method in the class that it's an instance of
  • With private, you can't access variables or call variables/methods outwith the class. (so instances of the class can't call private methods, but you can still call those methods inside of the class/from other methods in that class)
  • Protected is the exact same thing as private, but it allows variables/methods to be inherited by subclasses

It should be known that the practice of using public, private and protected to restrict what variables/methods an object can access or call is known as encapsulation.

I hope this article has helped you understand the different access modifiers. If you have any questions or advice, please feel free to comment themt. Have a nice day!