Non-static variable cannot be referenced from non-static context

Asked

Viewed 1,090 times

4

I’m using a context where I have an array type variable with reference to another class. When trying to declare the instantiated object of the class and declare its size is returned this error and I would like to understand why:

non-static variable cannot be referenced from a Static context

The error line is e1.empregados = new Funcionario[TAM]; in:

public class EmpresaTest
{
public static int posicao = 0;
public static boolean t = true;
public final int TAM = 5;



public static void main(String[] args)
{


    Funcionario f1 = new Funcionario();
    Funcionario f2 = new Funcionario();
    Funcionario f3 = new Funcionario();
    Funcionario f4 = new Funcionario();

    Empresa e1 = new Empresa();

    e1.empregados = new Funcionario[TAM];

    t = Booelan.parseBoolean(e1.adicionaEmpregado(f1));
    System.out.println("T: " + t);

    e1.adicionaEmpregado(f2);
    e1.adicionaEmpregado(f3);

    e1.contemFuncionario(f1);
    e1.contemFuncionario(f2);
    e1.contemFuncionario(f3);
    e1.contemFuncionario(f4);


    /*e1.empregados[0] = f1;
    e1.empregados[1] = f2;
    e1.empregados[2] = f3;*/
    }
    }

public class Empresa
{    
public  int idEmpresa;
public  int razaoSocial;
public  String cnpj;
public  Funcionario empregados[];

public int getIdEmpresa() {
    return idEmpresa;
}

public void setIdEmpresa(int idEmpresa) {
    this.idEmpresa = idEmpresa;
}

public int getRazaoSocial() {
    return razaoSocial;
}

public void setRazaoSocial(int razaoSocial) {
    this.razaoSocial = razaoSocial;
}

public String getCnpj() {
    return cnpj;
}

public void setCnpj(String cnpj) {
    this.cnpj = cnpj;
}

public Funcionario[] getEmpregados() {
    return empregados;
}

public void setEmpregados(Funcionario[] empregados) {
    this.empregados = empregados;
}

public void adicionaEmpregado(Funcionario f)
{
    int i = 0;

    if(this.empregados[i] != null)
    {
        this.empregados[i] = f;
        i++;
    }
    else
    {
        System.out.println("Não dá para adicionar mais funcionários");
    }

    /*for(int i = 0; i < empregados.length; i++)
    {
        this.empregados[i] = f;
    } */

}

public void mostrarEmpregados()
{
    for(int i = 0; i < empregados.length; i++)
    {
        System.out.println("Valor: " + i + " é o empregado: " + this.empregados[i]);
    }
}

boolean contemFuncionario(Funcionario f)
{
    boolean func = false;
    for(int i = 0; i < empregados.length; i++)
    {
        if(this.empregados[i] == f)
        {
            System.out.println("Empregado existente!");
            func = true;
        }
        else
        {
            System.out.println("Não encontrado!");
            func = false;
        }
    }
    return func;
}

1 answer

3

The problem in this case is that you are trying to access an instance variable in a static context.

Instance variables belong to the scope of a given object, an instance of a class.

If for example you do:

public class Foca {
    public int qtdFilhos;
}

Means that each instance of the class Foca (an object) will have a proper value for the variable qtdFilhos.

In that code:

public class Foca {
    public int qtdFilhos;

    public static void listarFamilia() {
        Foca[] familia = new Foca[qtdFilhos + 2];
    }
}

Access to the variable qtdFilhos in this method makes no sense, because which of the class objects Foca are you referring? It’s the same situation with the class EmpresaTest. When accessing the attribute TAM, which of the instances you refer to (we know that there may be only one or a specific variable, but the compiler does not)?

To fix the problem you need, as well as the other attributes above it, add the modifier static, making her a class variable.

As class variables are unique to all instances of a class on the same ClassLoader.

This means that for any time during the execution of your program, from the first access, that is where the ClassLoader initializes it, except in the case where the variable is final (the JVM does an optimization where the value is initialized along with the bytecode), any access to it will be shared by all.

To fix the problem change your code to:

public class EmpresaTest {
    public static int posicao = 0;
    public static boolean t = true;
    public static final int TAM = 5; // Agora TAM é uma variável de classe

    // Restante do código
}

Browser other questions tagged

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