Reputation: 2782
Is there any technique where you can use the return value of a non-static method from some class in a static method of some other class?
Upvotes: 0
Views: 2613
Reputation: 3743
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(); ..... } }
Upvotes: 0
Reputation: 41137
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.
Upvotes: 0
Reputation: 424993
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();
}
}
Upvotes: 2
Reputation: 346270
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.
Upvotes: 5
Reputation: 7597
If you're calling a non-static method, you have to do so against an instance of the class containing that method.
Upvotes: 0