How can I take a private variable in another class in Java?

Asked

Viewed 89 times

-1

I’m having a question about how I can catch one private variable in another class. I’m wanting to put all in private so I have better control and organization. Example:

Class Inicio

Private int Numero = 0;


Class Final
  //Quero pegar a variável privada da classe Inicio nesta classe

1 answer

0


The shortest and laziest answer is, you create a public method getNumero() in class Inicio which returns the private number, and calls this method in the class Final. But this is wrong.

In object orientation, the public interface of a class (i.e., its public methods) is separated from its internal implementation (private variables). In other words, the variable numero is an implementation detail and should not be exposed via public method if it does not make sense for the use you want to make of the class. A Start object should only expose the number if it is needed outside the Start class.

Now if you just need to ask Start if the number is greater than 10, then you create a method public boolean númeroEhMaiorQueDez() { return numero > 10; } and ask the object that question. In other words, there is no 1-to-1 relationship between the variables and the public methods of the object, it will depend on what you need the object to do, which depends on what it represents and (indirectly) what it contains.

  • Thank you very much helped me, I was failing it, because a friend of mine ultiliza private in all its variables, and I was wondering if this was right! I also have another question! What is when I can ultimalize Static? If you can answer me via coméntários I thank you very much! Thanks again for the help!

  • Using private in variables is not wrong, it is wrong to publish these variables that represent an internal implementation of the object (hidden from who calls the object) through public methods getNumero() without seeing if it really makes sense.

  • Static: I answered there in your question about Static.

  • Thank you +1 Time!

Browser other questions tagged

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