I'm creating a multilingual program in Java. An error occurs when inserting R.string
data from an XML file as a string value.
public static final String TTT = (String) getText(R.string.TTT);
The error message is as follows::
Cannot make a static reference to the non-static method
I wonder why the error occurs and how to solve this problem.
java static-methods compiler-errors
The getText() method is non-static and cannot be called by the static method.
To understand the reason, you have to understand the difference between the two.
The instance method (non-static method) is created when a particular type (class) of an object is created and can be used within that object, as follows:
SomeClass myObject = new SomeClass();
To invoke an instance method, call with an object variable (myObject):
yObject.getText(...)
Similarly, you can invoke static methods with object variables, such as myObject.staticMethod()
. However, this method is not recommended because it is not a clear representation of the static method.
And the static and non-static methods are created and operated in different memory regions. The static method is created in the static data area, and the non-static method is created in the stack. Therefore, the static method is created at the start of the program and can be used until the program ends, and the non-static method is created when the object is created and disappears together when the object disappears.
I'll explain it with the following class written in virtual code:
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
You can create and use objects in the class as follows::
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
What values do each field have?
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
TTT is a static field that is shared by all objects in that class. In this sense, the following example would be a problem
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
Why is TTT a static field here? Why isn't getText() a static method?
To solve the above problem, we can only remove the keyword static. However, without an understanding of how each type works, it can only be a stopgap until the next error occurs.
© 2024 OneMinuteCode. All rights reserved.