So I just started programming and what not and this question has me tearing my hair off. It's asking "Under what circumstances, if any, can a static method call an instance method?" I've tried going back to the chapters where it mentions both methods and get no hints. Can someone help?Would be appreciated.
-
3"When it has a reference to an instance on which it wishes to call the method"? – Jon Skeet Sep 24 '14 at 14:54
4 Answers
Static methods can always call instance methods - so long as they have a reference to an instance on which to call the method.
For example:
public static void main(String[] args) {
String foo = "hello";
System.out.println(foo.length());
}
length()
is an instance method on String
, main
is a static method, but I'm still fine to call it... because foo
provides a reference.
The only difference between static methods and instance methods in this regard is that an instance method implicitly has a reference to the type in which the method is declared - this
.

- 1,421,763
- 867
- 9,128
- 9,194
In order to call an instance method, you need an instance. So a static method can call an instance method as long as it has a reference to an instance to call it on.

- 55,782
- 14
- 81
- 108
Static methods can be called freely, but instance methods can only be called if you have an instance of the class. The static method needs to either get an instance from somewhere, or create one itself.
For example, the static method could create an instance of a class and then invoke an instance method on it:
class Foo {
static void staticMethod() {
Foo foo = new Foo();
foo.instanceMethod();
}
void instanceMethod() { }
}
Or the static method could be passed an instance by its caller.
class Foo {
static void staticMethod(Foo foo) {
foo.instanceMethod();
}
void instanceMethod() { }
}
These aren't the only ways, but they are common ones. What's required is that the static method gets its hands on an instance one way or another.

- 349,597
- 67
- 533
- 578
If the object is a parameter of the method -> sure But a static method can't work with non-static class variables, because these variables are specific for each instance of this class and static methods are independent of the object and only exist ONCE no matter how many objects of the class there are.
Does that explain it?

- 724
- 8
- 20