How to transform attributes into properties?

5

In C #, I can avoid using getter and setter , turning the attributes into properties, as below:

public class Pessoa {
    public int pes_idade { get; set; }
    public string pes_nome { get; set; }
}

Can you do this in Java?

    
asked by anonymous 26.08.2016 / 20:36

2 answers

5

In C # you create property that is nothing more than a private field (not attribute that is something else in C # ) with a couple of methods (can be one) that will give access to this field. You do not see them as methods (it's syntactic sugar) but that's what it is. It would be basically this:

public class Pessoa {
    private int idade;
    public int getIdade() { return idade; }
    public void setIdade(int value) { idade = value; }
    private String nome;
    public String getNome() { return nome; }
    public void setNome(String value) { nome = value; }
}

In Java you do not have this facility, so you have to do it on the hand, in exactly this way. Unless you use Lombok (see comments). I do not see people doing, there must be a reason (it may be just ignorance, but it seems that's not all that). See What is Lombok?

How this pattern works

This creates an indirection that is useful for versioning, dynamic loading of modules. Because the access logic passes to the method, so whenever you update the method in the class, everyone who calls you will receive the new execution, even if nothing that makes the access has been recompiled (only the component of the changed class is was recompiled).

If you used the direct field this would not be possible because access is made directly. A change in this class would require the recompilation of the entire application to ensure that the ignition was done according to the new operation.

So in some cases using the field is not a problem, even if in the future you need to switch to a method that has a processing. But if you are not sure that a change could affect the entire application, then you'd better ensure that by putting a method that does a pretty basic operation. What is the property in C #, or the pattern of getter and setter in Java.

I'm not a fan of the term attribute, I prefer field .

    
26.08.2016 / 20:47
-1

In Java it looks like this:

public class Pessoa {

    private String nome;
    private int idade;


    public String getNome() {
        return nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

}
    
26.08.2016 / 22:02