Since getText()
是非静态的,您不能从静态方法中调用它。
要理解其中的原因,您必须了解两者之间的区别。
实例(非静态)方法适用于特定类型(类)的对象。这些是用 new 创建的,如下所示:
SomeClass myObject = new SomeClass();
要调用实例方法,您可以在实例上调用它(myObject
):
myObject.getText(...)
However a static method/field can be called only on the type directly, say like this:
The previous statement is not correct. One can also refer to static fields with an object reference like http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html myObject.staticMethod()
but this is discouraged because it does not make it clear that they are class variables.
... = SomeClass.final
并且两者不能一起工作,因为它们操作不同的数据空间(实例数据和类数据)
让我尝试解释一下。考虑这个类(伪代码):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
现在我有以下用例:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
价值观是什么?
Well
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
换句话说,TTT
是该类型的所有实例共享的数据。所以说没有意义
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
所以问题是为什么TTT静态或为什么 getText() 不是静态的?
去除static
它应该会克服这个错误 - 但如果不了解你的类型的作用,它只是一个粘贴膏药,直到出现下一个错误。有什么要求getText()
要求它是非静态的?