java - 从方法内部对非静态方法进行静态引用

标签 java static static-methods non-static

我理解“无法对非静态方法进行静态引用”错误,但我遇到了这个:

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 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 Variables : Good or Bad? .

关于java - 从方法内部对非静态方法进行静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682750/

相关文章:

Flutter/Dart : Get URL from Shared Preferences Widget to use in Image. 网络小部件

java - "Java programming language type"的定义是什么

java - 尽管列为可用格式,但将 ogg 转换为 wav 不起作用

c - C 编译器优化局部静态变量是否合法?

java - 如何从android中的静态方法调用非静态方法

java - 从另一个类调用非静态 void

java - Facebook SDK 中的 R.Java 与应用程序 R.java 发生冲突

java - JDBC 类型 : -102 没有方言映射

PHP:如何制作可测试的静态方法

java - 为什么不使用 static void main 方法,而是使用非静态方法