Home > Programming, QA, Test and Automation Stuffs > Understanding encapsulation

Understanding encapsulation

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.

Image

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.

Advertisements
  1. August 14, 2013 at 10:15 pm

    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?

  2. August 28, 2013 at 3:10 pm

    Yes, of course !

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: