java – ¿Qué significa el mensaje de error non-static method <nombre> cannot be referenced from a static context?

Question:

I have a code as follows:

public class Clase {
    public void hazAlgo(String s) {
        /* implementación */
    }
}

Now I am creating a static method in Clase to validate that the string does not contain spaces on the sides. If you have them, you should clean them. In addition to that, the hazAlgo method must be used. So, I have the code like this:

public class Clase {
    public void hazAlgo(String s) {
        /* implementación */
    }

    public static String limpiaCadena(String s) {
        s = (s == null) ? "" : s.trim();
        hazAlgo(s);
    }
}

This code, when compiled, sends me the following error message:

$ javac Clase.java 
Clase.java:8: error: non-static method hazAlgo(String) cannot be referenced from a static context
        hazAlgo(s);
        ^
1 error

What am I doing wrong?

Answer:

The problem lies in understanding the meaning of static . The elements (attributes or methods) declared as static using the static modifier can be understood as elements that belong to the class and not to the instance of the class. In other words, static elements are global to the class that is loaded in memory. Here is an example of using a static method:

public class UnaClase {
    public static void log(String mensaje) {
        System.out.println("[LOG] " + mensaje);
    }
    public void logNoEstatico(String mensaje) {
        System.out.println("[LOG no estatico] " + mensaje);
    }
}

public class ClasePrincipal {
    public static void main(String[] args) {
        UnaClase unaClase = new UnaClase();
        unaClase.log("hola mundo"); //llamando a método estático desde instancia, es válido
        UnaClase.log("hola mundo"); //llamando a método estático directamente desde la clase, es válido porque el método estático le "pertenece" a la clase y no a las instancias

        unaClase.logNoEstatico("hola mundo"); //llamando a método no estático desde instancia, es válido
        //UnaClase.logNoEstatico("hola mundo"); //no se puede llamar al método no estático directamente desde la clase, no es válido
    }
}

Because these elements belong to the class and not to the instance, you cannot use elements of the instance to work with static elements. What does this mean? That a non-static attribute or method cannot be called from a static method. Let's review the method:

//el método limpiaCadena es estático, no necesita ninguna instancia
//de la clase para ser utilizado
public static String limpiaCadena(String s) {
    s = (s == null) ? "" : s.trim();
    //el método hazAlgo no es estático, entonces necesita
    //que se llame desde una instancia de la clase
    //como no existe una instancia aquí,
    //el compilador muestra el mensaje de error correspondiente
    hazAlgo(s);
}

How to solve the problem?

The simplest solution is to not use non-static methods or attributes directly within static methods . This is simply a mistake. If you have a situation where you "need" to call a non-static attribute or method within a static method, I am anticipating that you are making a serious design error. Warning posted.

A "simple" solution is to change the method from non-static to static, but you must understand the meaning of the change (if you don't understand the meaning, re-read from the beginning of the answer).

There are alternatives to this problem:

  1. Create the instance of the class inside the static method:

     public static String limpiaCadena(String s) { s = (s == null) ? "" : s.trim(); new Clase().hazAlgo(s); }

    Only use this if the class does not maintain state. However, this is a strange design and not recommended.

  2. Declare the class as an argument to the static method:

     public static String limpiaCadena(String s, Clase instancia) { s = (s == null) ? "" : s.trim(); instancia.hazAlgo(s); }

    This is a better alternative, cleaner in design but you will need more code.

Scroll to Top