0

I have question about static methods in Java. Why is that I can call a non-static method in another non-static method without specifying an instance of the class. For example if I have two non-static methods foo1() and foo2(), I can say foo2(){ foo() }. I can't do this in a static method. For example static void foo3(){ foo() }, this would not compile. Is this. implicit when you call other methods in a non-static method?

Thank you.

Kev Man
  • 47
  • 1
  • 5
  • @BrianRoach Not really. – assylias Feb 24 '13 at 08:24
  • @assylias Yes, really. If the OP were taking about a static method calling another static method in the same class ... we wouldn't be having this conversation because that works just fine as well. – Brian Roach Feb 24 '13 at 08:30

2 Answers2

6

Why is that I can call a non-static method in another non-static method without specifying an instance of the class.

Because it's implicitly calling it on this:

public void foo1() {
    foo2();
}

is equivalent to:

public void foo1() {
    this.foo2();
}

In a static method, there is no this to implicitly use as the target of the call.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

In a non-static context, you are in an instance of a class. You can call other non-static methods on that class, because you're calling that method on this. In a static context, you have no this, so you can't call methods without a particular instance.

Ian McMahon
  • 1,660
  • 11
  • 13