0

I was reading some code and I saw this:

abstract class Accum {

   /** Return the accumulated result. */
   abstract int result();

   /** Process and accumulate the value X. */
   abstract void accum(int x);

   /** Return the result of accumulating all of the values in vals. */
   int reduce(int[] vals) {
      for (int x : vals) 
        accum (x);
      return result ();
   }
}

How come reduce can call accum without referencing the object at hand with "this"? Doesn't this shorthand version of a function call work only for static methods? If this works, won't it blow up if both a static and non-static method have the same name?

2 Answers 2

2

On the contrary, you can't use this in a static function. The purpose of declaring a function static is to make it independent of an object instance- i.e., this object.

The call to accum (x); is inherently the same as this.accum (x);. The this keyword is implied.

In Java, overloading (i.e., functions with the same name) has nothing to do with whether a function is static or not.

Sign up to request clarification or add additional context in comments.

Comments

0

I assume this is java and answer based on that.

Since reduce is not a static method, that means an object has already been created therefore you can directly call another non-static method within the method. Otherwise it wouldn't be possible to call accum even with "this" keyword.

For your second question, you may only have exactly one method of the same name either static or non-static. Overloading a method is possible only if you have different parameters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.