1. Introduction

In this tutorial, we’ll study the difference between a method and a function.

2. Difference Between a Method and a Function

Functions and methods are analogous in many aspects; however, some important differences also exist. For this reason, we consider them conceptually separated when we’re working in the context of object-oriented programming:

functions methods

The first difference concerns the relationship between the function or method, on one hand, and the data or parameters on which they operate.

Functions require us to pass them all of their data explicitly. With the exception of global variables, if any, a function can only work with the data that we provide it.

Methods presume the existence of an object, which is passed implicitly when we call them. For this reason, a method can access all of the data that is associated with the class to which that object belongs.

Another difference concerns access to private data. If a class has any, its methods can operate with them. By contrast, any functions will be unable to do so.

3. Some Languages May Lack One

Finally, functions and methods differ because some languages lack one or the other:

In Java, for example, there are lambda expressions and functional interfaces, but they are a relatively recent addition.

In C, by contrast, there are functions but not methods. The language doesn’t have classes, and therefore it can’t have methods either.

In Scala, instead, there are both methods and functions.

4. Conclusion

In this article, we learned the differences between a method and a function.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.