Attribute or private field and getter and Setter in Java object-oriented programming

Asked

Viewed 125 times

2

In object-oriented programming in Java, when I create any attribute or private field, without their respective methods getter and setter has to define the attribute as final or need not?

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 lacks the methods getter and setter of the respective attributes or fields, in which case it would be necessary to define them as final?

  • It is not required. The keyword final is used to define a value that cannot be changed ( and therefore must be initialized together with the object ). If you want to have a private attribute and yet it is variable in its value. there is no need to declare it as final

1 answer

3


Usually the field shouldn’t be final. It may be, but it rarely makes sense, and never when there’s one Setter. The final determines that the value cannot be changed after initializing in the constructor. Is this what you want? The field will be immutable when you do that, and then a Setter will have no function, unless do in it something completely meaningless since what normal would change the value of the field associated with it.

What you call 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 take this opportunity to say that these methods should not always be used, contrary to what many say. Yes, to be 100% object oriented you should use, but what people don’t say is that you don’t always have benefits doing this and always have some harm, you need to decide if it’s worth it. There’s a question where I Linko several questions on the subject, take a browse there: Getters and Setters Methods.

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 the concepts in a way that makes sense.

  • "rarely makes sense" I think it often makes sense for the field to be final, and assign this modifier whenever possible. Make the field semantics clearer, if the field only needs to receive value once, in the constructor, I define it as final.

  • By the way, I took this "mania" of a recommendation on Soen to define an object synchronizationLock as final. I may be blindly repeating a "good practice", but the recommendation was taken from the book Effective Java, then I ended up considering valid for the general case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.