我理解"无法对非静态方法进行静态引用"错误,但我遇到了这个:
public class MyClass {
public static void main(String[] args) {
MyClass myClassInstance = new MyClass();
while (true) {
myClassInstance.myMethod();
myMethod();//Cannot make a static reference to the non-static method myMethod()
}
}// END main
void myMethod() {
try {
//Stuff
}
} catch (Exception e) {
myMethod();
}
}// END myMethod
}// END MyCLass
我不能只从main调用myMethod()但我可以从方法本身内部执行此操作(在这种情况下,如果发生异常,我想再次调用myMethod())。
这是如何运作的? 是myClassInstance仍然不知何故,因为那时我还在myMethod()里面?
在类级别拥有static MyClass myClassInstance = new MyClass()然后每次调用myClassInstance.myMethod()会更好吗?
当然你不能。 另一种方法是MyClass类的实例的一部分,而不是类本身。 你真的应该学习类和对象方法
myMethod是一个实例方法。 调用使用myMethod()相当于this.myMethod()。 在myMethod()中,这是一个实例方法,this存在:它是当前对象。 在main()里面,这是一个静态方法,没有this。 所以这个电话没有意义。
首先,您应该了解有关静态和非静态方法的更多信息:
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
参考:静态Vs非静态方法
How does this work? is myClassInstance still somehow there because at
that point I'm still inside myMethod()?
myMethod是属于myClassInstance的实例方法。 所以当你在myMethod()里面调用myMethod()时,它相当于this.myMethod()
Would it be better to have static MyClass myClassInstance = new MyClass() at class level and then call myClassInstance.myMethod() every time?
当我们将类的成员声明为static时,意味着无论创建了多少个类的对象,都只有一个静态成员的副本。 静态成员由类的所有对象共享。 如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。 有关更多信息,请访问静态变量:好还是坏?