Correct use of static variables within a class

0

I have a question about the use of the keyword reserved static when it is declared inside an object class. I have not been able to find an answer that clarifies me, I hope you can help me. I tell you an example of the scenario that has happened to me:

I have a class that defines an object, for example, Person. My program collects information from people in a file and for each reading of the file I create a Persona object. From another class, I collect all the collection of objects people I have created and for each one, depending on whether it is a man or a woman, for example, I take an action.

Inside the object, I had declared the variables as static, for example:

private static String sexo;
private static int edad;
...

While I am debugging, when I am collecting the information of each object, in the collection such that:

for (Object element : collection_){
        if (element instanceof Units){
            Units unit_ = (Units)element;
...

, I realize that in the objects of the collection I do not see these variables declared as static, but those that are declared without the static word I can see them (I mean when I put the mouse over the word collection_ and I see the drop-down with all the registered units). As soon as I have removed the static word from them, I have been able to see them during debugging.

My question is, why can not I see those declared as static if they are properties of my object? that is, I have them as global variables, with the word static set. I do not understand why with static post I can not see them and without static I can.

Sorry if the question is repeated, I come from .NET and there are Java things that I still have not completely clear, and this can not be clarified in any thread or with the java doc for this particular case. I hope that with the example can be worth, I just need to understand the concept well but put here the code I'm using is going to be worse because I use external libraries that can mess up the question.

Thank you very much.

    
asked by daniel lozano 02.01.2019 в 11:47
source

1 answer

1

First we must take into account that Static is used in several aspects of Java not only in variable but also in blocks of code, in methods, in classes, in imports, and relate but perform some somewhat different things. Given that the question is specifically with Variables, I will refer specifically to it. but for more information on static see: Static Class, Block, Methods and Static Import

syntax:

<modificador de acceso> static tipo_dato nombre_variable;

the variable static is a variable that is defined at the level of class (so does not belong to any instance , but to the Class as such) and can be say that it is a variable that is shared by all the instances of a class (they can access this variable) these variables are created when the class is loaded in memory (either when they are loaded dynamically or when the JVM starts)

when using variables static ? There are several scenarios for example, suppose that in your example you want to know the amount of Persona that are created. in this case we create a variable static counter:

static int contador=0 

(there are aspects of threading that may be necessary but that is not the focus of the question so ignore that for now)

now for example to perform the count you have to:

/*constructor de Persona*/
public Persona(...){
//...
//otras inicializaciones
//...
contador++;
}

In this way we have a variable that belongs to Person that has the total count of people Created and if necessary we can have a method ( static ) that tells us how many Persona has been created:

public static int getPersonaCount(){
    return contador;
}

or if the variable is accessible by other classes it can be accessed (public acces):

Persona.contador; 
// o dado getPersonaCount
Persona.getPersonaCount();

NOTE: it is also possible to access the static variables through the Object, but this is not recommended, for example:

Persona Maria= ...  
//...
Maria.contador; //-> se puede, pero no es recomendado, inclusive los IDE te lo indican: 

on the other hand as OP mentions:

private static String sexo;
private static int edad;

these variables in particular appear to be of the Person in particular (instance) so are not variables that are recommended to be static given that each person has different sex and age different are not shared attributes! what is shared is the binary of the sex in which case you can use variables static for the options (although it is advisable to use Enums for this but for demonstration of the example we use static)

public class Persona{
    //variable de sexo
    private Sexo sexoPersona;
//...
//definicion de la clase persona metodos, variables etc...
//...
//final para que nadie pueda modificar esta clase.
    public final static class Sexo {
       public static final Sexo MASCULINO  = new Sexo("masulino");
       public static final Sexo FEMENINO  = new Sexo("Femenino");
       private final String valor;

        private Sexo(String val) {
            valor = val;
        }

        @Override
        public String toString() {
            return valor;
        }

    }
}

In this case we can see that we create a class static which defines 2 constants estaticas static final generates a variable that can only be instantiated a single you see. (This way of creating variables is also used by the Singleton pattern, where the single instance is static final and instantiated only one instance.) This example is 2 instances and So much is not Singleton ...

How do we give a value of the person's sex? by using Persona.Sexo example:

//los siguientes variables son public(tanto la clase como la instancia)
//por tanto se puede utilizar dentro y fuera de la clase Persona,
//pero le pertenese a Persona:
Persona.Sexo.MASCULINO;
// o
Persona.Sexo.FEMENINO; 

finally

  

Why can not I see those declared as static if they are properties of my object?

This is because you are using Variables static wrong. the way in which this question is formulated determines: static si son propiedades de mi objeto , NO! on the contrary, if they are static they are NOT Variables of the Object, but of the Class and therefore shared By all instances of the Class aka (All Person objects)

  

when I put the mouse over the word collection_ and I see the dropdown with all the registered units

this is dependent on the IDE more than the use of static but eh assume that the reason is because the IDE prioritizes showing the variables of the object that the class for example in Netbeans can see the variables in a section for static:

    
answered by 02.01.2019 в 21:10