Get startedGet started for free

Encapsulation & access modifiers

1. Encapsulation & access modifiers

Welcome back, and now we will explore how to expose and hide properties by setting their access levels within a Java class, a concept known as encapsulation.

2. Understanding encapsulation

Encapsulation is similar to how a mobile phone operates. Users can utilize features like the screen and speakers without needing to understand the intricate inner workings of all the technology inside the phone. Users are only exposed to the device part they need to use. This principle applies only to classes in Java, where we manage property and method access using access modifiers.

3. Public properties

The public access modifier allows properties and methods to be accessed by any class instance. For example, consider a Car class that has a color property. By declaring this property as public using the public keyword, we can easily access and modify the color when we create an instance, such as myCar.

4. Private properties

Conversely, if we need to keep a property hidden from class instances, we utilize the private keyword. Let's say we add a model property to our Car class and mark it as private. This means that when we create an instance of the Car class, we cannot directly access the model property without our program failing, thereby making it inaccessible from outside the class.

5. Public methods

Just as properties can be public, methods can also be declared public. We can create a getModel() method in our Car class, which returns the value of the model property. This allows us to access the model without modifying it.

6. Private methods

Similarly, methods can be made private. For instance, we could add a private method called calculateSpeed() that computes the car's speed using a trademarked formula we don't want seen by others, while another public method, getSpeed(), retrieves the current speed.By keeping calculateSpeed() private, we ensure it is only used within the class and outsiders cannot alter it.

7. Static methods

The static keyword is helpful in situations where we want to use properties or methods without creating class instances. This is often used for helper classes. For example, we could create a Formula class with a static method getSquare() to calculate the square of a number. We can call this method directly using the class name, such as Formula.getSquare(5), and printing the line of code will return 25.

8. Recap

In summary, Java's access modifiers, including public, private, and static, help us control the visibility of class properties and methods, allowing us to design more robust and secure applications. We also learned how to use properties without creating instances by marking them with the static keyword.

9. Let's practice!

By applying these concepts in our classes, we enhance encapsulation and improve code maintainability.