Methods
In short: A function that belongs to a class and operates on the data of an object — the “ability” part of a class, as opposed to its pure data fields.
In more detail: Methods can accept parameters, return a value (or be void, i.e. return nothing), and via overloading be defined multiple times with different parameter lists. Access modifiers control from where a method may be called.
In Depth
The difference between a method and a “normal” function is purely organisational: a method is a function bound to a class and (for non-static methods) implicitly has access to the fields of the specific object it’s called on — this implicit reference is often called this/self.
class Rectangle {
double width;
double height;
double calculateArea() { // method - has access to width/height
return this.width * this.height;
}
}
Rectangle r = new Rectangle();
r.calculateArea(); // called ON a specific objectMethods can be roughly categorised by their effect: query methods return information without changing the object’s state (e.g. a getter), command methods change state, but often return nothing (or just a confirmation) (e.g. deposit()). This separation (“command-query separation”) is considered good style, because it makes it predictable what a method call does, without having to read its implementation.
A good method should ideally be short and focused on ONE clearly nameable task — a method that simultaneously validates data, writes to a database, and sends an email is hard to test and reuse. The rule of thumb “a method should fit on one screen” isn’t strict, but a useful warning sign for too much responsibility in one place.
See also: Parameters, void, Overloading, Classes