Monday 3 October 2011

Function Vs Method


Briefly explain the difference between a function and method?

“Cool, till now I thought both were synonyms” – My first reaction to this question when it was posed to me at one of the written test. You would be surprised to know that both are different and wonder why it didn’t occur to you in your long innings of programming. Do not worry; many are sailing in the same boat. Let us rescue us all through this discussion.

We have seen the concept of functions in ‘C’, methods in ‘JAVA’ and both in ‘C++’. This might ring a bell in your head. Yes, it’s correct; it has something to do with OO concepts. Through googling, I came to an understanding that,

Methods are dependent on the object. They can be invoked using the object i.e. object is an implicit parameter for method. They can access the member variables of the object.  So the calls to the method can return different values based upon the object invoking it.

Whereas functions is independent of the calling object. They can access only local variables, global variables and constants.  Hence, calls to a function with same parameters will return same value.

 Let us understand with simpler example, consider lion and deer as two objects, both can perform the function of sleep, but only lion can invoke the method of roar!






Now an interesting issue of classifying static method arises. Can it be called a function? Yes, to my understanding it can also be called a function as it shares its traits being independent of object and returning values upon being called.

You can find more information from this interesting discussion. So next time, do not miss to differentiate a function from a method.

Picture Source: Internet

4 comments:

  1. They are not same! I knew it already man! Herbert Schildt explains well in his C++ book.

    ReplyDelete
  2. Static methods are like functions, but not exactly. In certain situations even static methods depend on the internal state of static members.

    ReplyDelete
  3. Yes Ram, your are correct. That is why I carefully chose the words that "static method CAN ALSO be called as function" instead of "static method is a function".

    ReplyDelete
  4. Post more like this.. Will be quite interesting to debate.

    ReplyDelete