Generally in interview it is asked what is the difference between a method and a function.
We make use of two terms namely function and method in programming language. But there is difference between the two.
Function :-
- Function is defined in structured programming language like C, Pascal and in object based language like java script.
- Function is self describing code.
- Function is free from class that means we can define a function outside a class.
- Function is having its own existence.
- We can also say a function is not associated with an object.
Example:-
void sum()
{
int a=7,b=8;
printf(“sum =%d”,a+b);
}
Method:
- The term method is used in case of object oriented programming language for example Java , C#.
- Method is defined inside a class.
- Methods are associated with an object that means a method can be invoked with the help of an object
- Methods are used to manipulate objects.
Example:-
class arithmetic
{
int a,b,c;
public void add()
{
c=a+b;
Console.WriteLine("Sum of two numbers is : {0}",c);
}
}