简体   繁体   中英

Incorporating a non-static return value into a static method?

有什么技术可以在某个其他类的静态方法中使用某个类的非静态方法的返回值?

The corrent word for a non-static method is instance method , because it can only be invoked on an instance of its class. So what you need is an instance of the class created with new , then you can invoke instance methods on it.

I suggest reading the introduction to OO concepts in the Java tutorials.

It's hard to know what you're trying to do without any code (even an attempt would be good), but...

Maybe you want the singleton pattern:

public class MyClass {
    private static final MyClass INSTANCE = new MyClass();
    private MyClass() {}
    public static MyClass getInstance() {
        return INSTANCE;
    }
    public int someMethod() {
        // return some value;
    }
}

then from the other class:

public class TheirClass {
    public static int whatever() {
        return MyClass.getInstance().someMethod();
    }
}

创建该类的实例,然后return instance.method();

In the static method, create an instance of the class where non-static method is, and call the non-static method on the created object.

There is no other way, because a non-static method can call other non-static static methods, and it can also use the reference to the class instance("this"); so it can only be called on an instance of the class:

public class A{

 public int NonStaticMethodA() { int val; ..... return val; } public int NonStaticMethodB() { int val=this.NonStaticMethodA(); ..... return val; } 

}

public class B{

 public static void StaticMethod() { A a = new A(); int value = a.NonStaticMethodB(); ..... } } 

如果要调用非静态方法,则必须针对包含该方法的类的实例进行调用。

As long as an object of the other type is available within the static method, you can just call the method on that object.

The object can be created within the static method, passed into it as a parameter, or be a static field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM