error: non-static variable this cannot be referenced from a Static context / Java 8

Asked

Viewed 20 times

0

I am doing a URI (online Judge) exercise but is showing "Compilation error" due to error:

Main.java:8: error: non-static variable this cannot be referenced from a Static context Interfacetext i = new Interfacetext(); ^ 1 error

Follows the code:

import java.util.Scanner;
import java.io.IOException;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        InterfaceTexto i = new InterfaceTexto();
        i.executar();
    }
class InterfaceTexto
{
    private Scanner entrada;
    private Fibonacci fibonacci;
    private int n;
    private int t;

    public InterfaceTexto()
    {
        entrada = new Scanner(System.in);
        fibonacci = new Fibonacci();
    }
    
    public void executar()
    {
        t = entrada.nextInt();
        
        for(int i = 0; i < t; i++)
        {
            fibonacci();           
        }
    }
    
    public void fibonacci()
    {
        n = entrada.nextInt();
        System.out.printf("Fib(%d) = %d\n", n, fibonacci.numeroFibonacci(n)); 
    }
}
class Fibonacci
{
    private int[] fib;
    private int n;
    private static final int TAM = 61;

    public Fibonacci()
    {
        fib = new int[TAM];

        fib[0] = 0;
        fib[1] = 1;

        for (int i = 2; i < TAM; i++)
            fib[i] = fib[i-1] + fib[i-2];
    }

    public int numeroFibonacci(int n)
    {
        int numero = fib[n];

        return numero;
    }
}
}

1 answer

0

Quick fix

Key missing to close Main class.

public class Main {
    public static void main(String[] args) throws IOException {
        InterfaceTexto i = new InterfaceTexto();
        i.executar();
    }
// aqui
}
    class InterfaceTexto
    {
        ...
    }

Understanding the problem

  • When you didn’t lock the class key Main, Interfacetext has become an inner class.
  • To instantiate the inner class from a (non-static) method of the class would look like this:
    public void anyMethod() {
        InterfaceTexto i = new InterfaceTexto();
    }

But when you tried to instantiate from the method main, you found this error:

non-static variable this cannot be referenced from a static context

What the mistake is saying is:

  • non-static variables (referring to class InterfaceTexto) cannot be referenced in static context.
  • the static context is because you are inside the method main
  • If the problem involved declaring the inner class static, then you could instantiate an object inside main as you did! But I don’t think that’s the best way.
static class InterfaceTexto {
...
}

References for reading

See here a good reading on internal/nested classes here from Sopt

Browser other questions tagged

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