Nate
Nate

Reputation: 117

Different ways of calling methods?

I'm told that this is one way of calling a method:

If you write just the name of the method or property, Java will make a guess as to what you were meaning to write before the name, based on the following rules

  1. If the method is NOT static, it will try to find a non-static method/property with the name, then look for a static method/property
  2. If the method IS static, it will try to find a static method/property only

Could anyone give me an example of this? I'm having trouble understanding what it means, since how could it know whether the method is static or not before it finds the method, but it finds the method based on whether its non static or static? Or are there two different methods they're referring to or something?

Upvotes: 0

Views: 160

Answers (1)

linasj
linasj

Reputation: 56

Here is an example with appropriate comments of what would happen in the methods c, d and e:

class A {
    // methods to be looked up
    // a static method
    static void a() {};
    // non-static method
    void b() {};


    static void c() {
         // valid reference to another static method
         a();        
    }

    static void d() {
         // This would fail to compile as d is a static method 
         // but b is a non-static
         b();        
    }

    // non-static method would compile fine
    void e() {
       a(); // non-static method can find a static method 
       b(); // non-static method can find another non-static method
    }

}

Upvotes: 2

Related Questions