我理解“无法对非静态方法进行静态引用”错误,但我遇到了这个:
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()
会更好吗?
最佳答案
首先你应该了解更多关于静态和非静态方法的知识:
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.
引用:Static Vs Non-Static methods
How does this work? is
myClassInstance
still somehow there because at that point I'm still insidemyMethod()
?
myMethod
是属于 myClassInstance
的实例方法。因此,当您在 myMethod()
内调用 myMethod()
时,它相当于 this.myMethod()
Would it be better to have
static MyClass myClassInstance = new MyClass()
at class level and then callmyClassInstance.myMethod()
every time?
当我们将类的成员声明为静态时,这意味着无论创建该类的多少个对象,都只有一份静态成员的副本。静态成员由类的所有对象共享。如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。欲了解更多信息,请访问Static Variables : Good or Bad? .
关于java - 从方法内部对非静态方法进行静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682750/