7.5 Encapsulation
Hello everyone In this video, we will see what encapsulation Encapsulation is about defining the visibility and accessibility of properties and methods of a class to better control their use. So for this it is enough to declare «private» the data to be encapsulated and to define methods to read them and to modify them So we call these methods the "getters" for the reading and setters for the modification. So let’s make an example to better understand. We will create a "Employee" class which will have as property name which is a String, an ID which is an int and salary which is also an int. So I can easily use these classes in our class "Main" Now we will create an object "Employee" in the class Main. So, "Employ" new Employ As we can see We can access the variables, ID, name, Salary So it’s an easy program that we can do but in order to secure our programs when we have a large number of programs and a large number of lines in a program so we need encapsulation at this time-there so that the data can be secured so for that, I will put it . put my variables in private. We go to the "Employee" class, put all our variables in private. Now in the "Main" class I can no longer use them. As we can’t use them, we need the getters and setters So again, we go to the "Employee" class and we press Alt + Insert Then we choose "getter" and "setter" Now we have our getters and setters. We can go to the "Main" class. And here we see all the setters and getters e.setID Number 6. In fact the same for the name and salary the name will be "Paul" and the salary will be 30000 Now we will display them. First the name So, name this time, it is not in "set" but "get" So, e.getName The same thing for ID And the same thing for salary So, to do "System.out.println" Easily, just "sout" then tab it directly After we do in brackets salary. getSalair Now we launch the program to see if it works and as we can see. We do have the name ID and Salary So I hope you understand the concept of encapsulation, so the concept is that all the variables, are accessible via methods so for this, we use getters and setters for that.That’s all for this video. In the next video, we’re going to do a little challenge on encapsulation to better understand So I’ll tell you next time!