I have a code as follows:
public class Clase {
public void hazAlgo(String s) {
/* implementación */
}
}
I am now creating a static method in Clase
to validate that the string does not contain any trailing spaces. If you have them, you should clean them. In addition to that, the method must be used hazAlgo
. 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, gives 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?
The problem lies in understanding the meaning of
static
. The elements (attributes or methods) declared as static by means of the modifierstatic
can be understood as elements that belong to the class and not to the class instance. In other words, static elements are global to the class that is loaded into memory. Here is an example of using a static method:Since these elements belong to the class and not to the instance, you cannot use instance elements 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:
How to solve the problem?
The simplest solution is to not use attributes and non-static methods directly inside 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'm telling you that you're making a serious design mistake. Warning posted.
A "simple" solution is to change the non-static method 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:
Create the class instance inside the static method:
Only use this if the class does not maintain state. However, this is a strange design and not recommended.
Declare the class as an argument to the static method:
This is a better alternative, cleaner in design but you will need more code.
Or just call the method like this:
Taking your published code, it would be like this:
I think this might work too: https://docs.google.com/document/d/1oKikiQtWVeFpkrhLrSceermh54-K14oSOYp29WLCHXc/edit?usp=sharing
To put it in code instead of images it would be:
Before (with error)
After (no error):