简体   繁体   English

将非静态返回值合并到静态方法中?

[英]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. 非静态方法的相应单词是instance method ,因为它只能在其类的实例上调用。 So what you need is an instance of the class created with new , then you can invoke instance methods on it. 因此,您需要的是使用new创建的类的实例,然后可以在其上调用实例方法。

I suggest reading the introduction to OO concepts in the Java tutorials. 我建议阅读Java教程中有关OO概念介绍

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"); 没有其他方法,因为非静态方法可以调用其他非静态静态方法,并且还可以使用对类instance(“ this”)的引用; so it can only be called on an instance of the class: 因此只能在该类的实例上调用它:

public class A{ 公开课A {

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

} }

public class B{ 公开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. 该对象可以在静态方法中创建,可以作为参数传递给它,也可以是静态字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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