Encapsulation and Java Access Modifiers

Asked

Viewed 234 times

9

A very simple question:

Given that class:

public class User {

  private String nome;

  //get/set

  public boolean fazQualquerCoisa(){
    **duvida**.equals("algumacoisa");
 }
}

Within the method did All() I must access the name directly or using the get method?

nome.equals ou getNome().equals?

1 answer

10


It depends a lot on what your method fazQualquerCoisa() and how the getter of your String, if inside the getter he only has one return nome; so whatever, if there is any specific treatment of your String that must be done before it is called within the method, then the access must be done through the getter.

As we can see in this topic: Getters and setters are an illusion of encapsulation?, often people make the getters and setters solely and exclusively because they are used to doing so and in fact are not encapsulating anything, if that is the case, fits in the first case I quoted: whatever.

  • Thank you so much for clarifying that for me!

Browser other questions tagged

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