There are no functions per se in Java. All you've got is methods. To imitate functions, Java generally uses static methods (as in java.lang.Math
).
There is a number of object-oriented languages that provide free-standing functions, though: among them Python, Ruby, JavaScript, C++, Object Pascal, and even (yuck) PHP. There's a good reason behind that.
A method is basically a function with one extra parameter (invisible in Java). You refer to it as this
. That this
thing allows you to access the object whose method is being called, so you can think that the entire object is always an implicit parameter to a method, additionally to parameters you normally define.
A method makes sense if it makes use of its object: calls other methods and/or accesses data members. For example, a list can have a getLength()
method that knows how to calculate list's length, e.g. by scanning each member. It obviously uses the implicit this
object, that is, the list. This is why it needs no explicit parameters.
Else, a function is enough. For instance, to compute a cosine of an angle you only need the angle, and no other state, so cos(float angle)
could be a function, and only depend on the explicit angle
parameter.
Another important thing is method overriding. (To my ming, this is a dubious practice, but Java uses it very widely.) You declare a certain class (call it Z
) a subclass of another class (call it A
), and change implementation of some of its methods (suppose we overrode method foo()
).
The subclass works like the base class (it is said to provide the same interface) but does it by different means. According to Liskov substitution principle, you can declare a variable of type A
, assign to it an instance of type Z
, and invoke method foo()
; what will be invoked is Z
's implementation of foo()
, not A
's. That is, the method to call will be looked up at runtime, based on the actual type of the object. This is know as "dynamic method dispatch" or "virtual methods".
What method overriding provides automatically is not easy to directly emulate with functions. (With functions, similar things are usually done with "callbacks" or "higher-order functions").
In certain languages, such as Java and C#, you can define "static methods" that do not receive a this
parameter. They work exactly like "standalone" functions and use the class as a namespace. Such namespacing may sometimes make sense, when a static method of a class is used to look up or create new instances of that class.
I hope you now have a better picture.
method
is just a special case of "function" attached to an object. Many languages, like JavaScript, even use the keywordfunction
when writing methods.