Difference between “Function“ and “Method“ in programming
Two words someone could think are synonyms. They are not!
Introduction
When I started programming using Java I learned there was just Methods. It is right. In java there are no functions. Someone around me though sometimes used to talk about functions in Java. It was confusing!
Let’s see the differences considering Golang, Java and C++.
Function
A set of instructions that perform a task and it is not linked to an object or a class. It is a scope like this (example using Golang):
func sum(a,b int) int {…}
A function is called in the following way:
sum(3,5)
In Java functions don’t exist as all instructions are in classes! In Java exist methods though.
Method
A set of instructions that perform a tasks and it is linked to an object or a class. More precisely we can say it is a “function“ with a receiver argument. What does it mean? A method is a “function“ that can be called only by some structures. Example using Golang:
type Complex struct{
real int
imm int
}
func (c *Complex) sum(a Complex) Complex{…}
(c *Complex) is the receiver argument. This means that our “sum“ method defined above can be called in the following way just with Complex types.
complexNum := Complex{3,5}
complexNum.sum(Complex{7,2})
This method will intuitively sum two complex numbers returning the result.
Differences
A function is called in the following way:
function()
A method is called in the following way:
type.method()
In java
In java there are static methods and non-static methods. Both of them are in a class!
A static method will be called like:
class.method()
A non-static method will be called like:
object.method()
In C++
In c++ exist both, like in Golang. What in Java are static methods, in c++ it is represented by functions. Example:
void function (){…}
int main(){
function ();
return 0;
}
What in Java are non-static methods, in c++ are represented by methods. Example:
class Example{
public:
Example(){…} //default constructor
void method(){…} //a method
};
int main(){
Example example;
example.method();
return 0;
}
Conclusion
I tried to make you understand the difference between functions and methods in programming. I hope I completed successfully the task and I added value to your knowledge.
Stay tuned for the next daily articles!
What is the difference between “Argument“ and “Parameter“ in programming? Consider reading the article below.
Do you know the difference between “Syntax Errors“ and “Logical Errors“? I explained it in the article below.
Thank you for having read my article. I hope I added value to your knowledge.
Consider following me and subscribing below with your email to know when I publish the new daily articles.
Did you enjoy reading it?
Support me. Use the link below to become a Medium member.
Support my writing by becoming a Medium member today and get full access to all the stories on Medium. Click on “Medium member” above for the link. No extra costs for you!