Attribute and private field and getter and setter in object-oriented programming in Java

2

In object-oriented programming in Java, when I create a particular attribute or private field, without its methods getter and setter do you have to set the attribute to final or do not require?

For example:

public class Pessoa {

    private String nome;
    private String endereco;
    private int idade;
    private double salario;

    public Pessoa(String nome, String endereco, int idade, double salario) {
        this.nome = nome;
        this.endereco = endereco;
        this.idade = idade;
        this.salario = salario;
    }

}

In this class above as you see, it does not have the methods getter and setter of the respective attributes or fields, in which case it would be necessary to define them as final ?

    
asked by anonymous 03.11.2018 / 12:43

1 answer

2

Normally the field should not be final . It may be, but it rarely makes sense, and never when it has a setter . The final determines that the value can not be changed once it is initialized in the constructor. Is that what you want? The field will be immutable when you do this, and then a setter will have no function whatsoever, unless you do something completely meaningless in it since what you would normally change is the value of the field associated with it.

What it calls attribute actually calls field . I know, it's not your fault, everyone even teaches wrong. In English the correct terms are getter and setter .

And I'd like to say that these methods are not always to be used, contrary to what many people say. Yes, to be 100% object oriented you should use it, but what people do not talk about is that you do not always have benefits doing this and always have some wrongdoing, you need to decide if it's worth it. There is a question where I linko various questions on the subject, navigate there: Getters Methods and Setters .

The original question had other conceptual problems, programming has a lot to do with conceptualizing things correctly, especially in object orientation, which is to organize concepts in a way that makes sense.

    
03.11.2018 / 13:00