Methods Declaration
A method is a function. It could be declared in any order into a Class body.
Method Header
- return type
- name
- parameters
return: Whenever a return statement is encountered, the method stops executing as of that line of code, and execution control immediately returns to the code that invoked the method in the first place.
void doSomething () { return; }
A method body is permitted to include more than one return statement. Good programming practice, however, is to have only one return statement in a method, at the very end.
Methods implements business rules
In a sense, even a method header expresses a simple form of business rule/requirement. But, the details of an application’s business rule(s) are encoded in its various classes’ method bodies.
Method Overloading
Overloading is a language mechanism that allows two or more different methods belonging to the same class to have the same name as long as they have different argument signatures.
void print(String fileName) { ... // version #1
void print(int detailLevel) { ... // version #2
void print(int detailLevel, String fileName) { ... //
version #3 int print(String reportTitle, int maxPages) { ... //
version #4 boolean print() { ... // version #5
The ability to overload methods allows us to create an entire family of similarly named methods that do essentially the same job.
Note that there is no such thing as attribute overloading; that is, if a class tries to declare two attributes with the same name.
Delegation
If a request is made of an object A and, in fulfilling the request, A in turn requests assistance from another object B, this is known as delegation by A to B.