JavaRush /Java Blog /Random EN /Encapsulation Principles in Java

Encapsulation Principles in Java

Published in the Random EN group
Hello! Today's lecture will be devoted to encapsulation and we will start it right away with examples :) In front of you is a familiar soda machine. I have one question for you: how does it work? Try to answer in detail: where the glass comes from, how the temperature inside is maintained, where the ice is stored, how the machine understands what syrup to add, etc. Most likely, you do not have answers to these questions. Well, maybe not everyone uses such machines; they are not so popular nowadays. Let's try to give another example. Something you know you use many times every day. Oh, I have an idea! Encapsulation Principles - 2 Tell us how the Google search engine works . How exactly does it search for information based on the words you entered? Why are these results at the top and not others? Even though you use Google every day, you probably don't know it. But it is not important. After all, you don't need to know this. You can enter queries into a search engine without thinking about how exactly it works. You can buy soda from a vending machine without knowing how it works. You can drive a car without delving into the operation of the internal combustion engine, and without knowing physics at all, even at school level. All this is possible thanks to one of the main principles of object-oriented programming - encapsulation . While reading various articles on this topic, you probably came across the fact that there are two common concepts in programming - encapsulation and hiding . And by the word “encapsulation” the authors mean one thing or another (as it happens). We will break down both terms so that you have a complete understanding. The original meaning of the word “ encapsulation ” in programming is the combination of data and methods of working with this data in one package (“capsule”). In Java, the class acts as a capsule package . A class contains both data (class fields) and methods for working with this data. Encapsulation Principles - 3 This seems obvious to you, but in other programming concepts everything works differently. For example, in functional programming, data is strictly separated from operations on it. In OOP (object-oriented programming), programs consist of capsule classes, which are both data and functions for working with it. Now let's talk about hiding . How is it that we use all sorts of complex mechanisms without understanding how they work and what their work is based on? It's simple: their creators have provided a simple and user-friendly interface. On a soda machine, the interface is buttons on a panel. By pressing one button, you select the volume of the glass. By pressing the second one, you select the syrup. The third is responsible for adding ice. And that's all you have to do. It doesn't matter how exactly the machine is designed inside. The main thing is that it is designed in such a way that to get soda, the user needs to press three buttons . It's the same with a car. It doesn't matter what's going on inside him. The main thing is that when you press the right pedal, the car goes forward, and when you press the left pedal, it slows down . This is precisely the essence of concealment. All the “insides” of the program are hidden from the user. For him, this information is superfluous and unnecessary. The user needs the end result, not the internal process. Let's look at the class as an example Auto:
public class Auto {

   public void gas() {

       /*some complicated things are happening inside the car
       as a result of which it goes forward*/
   }

   public void brake() {

       /*some complicated things are happening inside the car
       as a result of which it slows down*/
   }

   public static void main(String[] args) {

       Auto auto = new Auto();

       // How everything looks to the user

       //pressed one pedal - went
       auto.gas();

       //pressed another pedal - braked
       auto.brake();
   }
}
This is what implementation hiding looks like in a Java program. Everything is like in real life: the user is provided with an interface (methods). If he needs the car in the program to perform an action, he just needs to call the desired method. And what happens inside these methods is unnecessary information, the main thing is that everything works as it should. Here we talked about hiding the implementation . Besides this, Java also has data hiding . We wrote about it in the lecture about getters and setters , but it wouldn’t hurt to remind you. For example, we have a class Cat:
public class Cat {

   public String name;
   public int age;
   public int weight;

   public Cat(String name, int age, int weight) {
       this.name = name;
       this.age = age;
       this.weight = weight;
   }

   public Cat() {
   }

   public void sayMeow() {
       System.out.println("Meow!");
   }


}
Perhaps you remember from the last lecture what the problem of this class is? If not, let's remember. The problem is that his data (fields) are open to everyone, and another programmer can easily create a nameless cat in the program with a weight of 0 and an age of -1000 years:
public static void main(String[] args) {

   Cat cat = new Cat();
   cat.name = "";
   cat.age = -1000;
   cat.weight = 0;

}
In such a situation, you can closely monitor whether one of your colleagues is creating objects with the wrong state, but it would be much better to exclude the very possibility of creating such “wrong objects”. Encapsulation Principles - 4 They help us with data hiding:
  1. access modifiers ( private , protected , package default );
  2. getters and setters.
There we can, for example, check whether someone is trying to assign a negative number to the cat as its age. As we said earlier, the authors of various articles on encapsulation mean either encapsulation (combining data and methods), or hiding, or both. Java has both mechanisms (this is not necessarily the case in other OOP languages), so the latter option is the most correct. Using encapsulation gives us several important advantages:
  1. Monitoring the correct state of the object. There were examples of this above: thanks to the setter and the private modifier, we protected our program from cats with weight 0.

  2. User-friendliness due to the interface. We leave only methods “outside” for user access. All he needs to do is call them to get the result, and he doesn’t need to delve into the details of their work at all.

  3. Changes to the code do not affect users. We make all changes inside methods. This will not affect the user: he wrote auto.gas() for the gas of the car, so he will write it. And the fact that we changed something in the operation of the gas() method will remain invisible to him: he, as before, will simply receive the desired result.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION