Difference between Methods and Functions
A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).
All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.
- It is implicitly passed the object for which it was called
- It is able to operate on data that is contained within the class (remembering that an object is an instance of a class – the class is the definition, the object is an instance of that data)
(this is a simplified explanation, ignoring issues of scope etc.)
- Functions have independent existence means they can be defined outside of the class. Ex:- main() function in C, C++ Language
- Functions are called independently.
- Functions are self describing unit of code.
- I was taught that “A Function should do 1(one) thing and do
- Methods do not have independent existence they are always defined with in class. Method is tied to a specific class. Ex:- main() method in Java that is defined with in a class
- Methods are defined in object oriented languages like C#, Java
- Methods are called using instance or object.
- Methods are used to manipuate instance variable of a class.