This technique is used to hide an idea, when you don’t want expose the inter details to the users.
As a more technical example we can describe what happens in a sales system, where we have records of employees, users, managers, clients, and other products. If happens a problem in the user, only this sector will be fixed and does not affect the others.
In a process of encapsulating the attributes of the classes are kind of private. To access these types of modifiers, you must create getters and setters methods.
The methods setters are used to change the information of a property of an object, and getters to return the value of this property.
See an example of encapsulation, in Listing 2 creates the attributes private (private) and is carried out the process of generating getters and setters methods.
Code:
public class Funcionario {
private double salario;
private String nome;
public String getNome() {
return
nome;
}
public void setNome(String nome) {
this
.nome = nome;
}
public void setSalario(double salario) {
this
.salario = salario;
}
public double getSalario() {
return
salario;
}
}
So, is instantiated class “Employee”, where the variable reference is used to invoke methods setters, reporting any data. In the end, the getters is used within the “System.out.println” to output the results that were passed in the methods setters.
Code:
public class TestaFuncionario {
public static void main(String[] args) {
Funcionario funcionario =
new
Funcionario();
funcionario.setNome(
"Thiago"
);
funcionario.setSalario(2500);
System.out.println(funcionario.getNome());
System.out.println(funcionario.getSalario());
}
}
This is easy and helps you avoid pass a lot of parameters in methods, classes and functions.
I am in school and like coming across blogs that are very similar to whatever I will
be studying. Can I cite you within my report together with a
blog mention?
Yes, of course !