Today, we learned about functions/methods. When you have a long program, it can help to break it down into smaller groups of functionality. A function/method groups a sequence of statements and provides a well defined, easy to understand functionality which can be reused. A method takes input, performs an action or a series of actions, and produces an output. In Java, each method is defined within a class. An example of a standard method is System.out.println().
To define your own method, you must declare it with a header.
class MyClass
{
static int methodName (int parameter1, int parameter2){ //This is the header
//The method body goes here
}
}
You close the body of a method with a return statement. The return type of a method indicates the type of value that the method sends back to the calling location. A method that does not return a value has a void return type in the heading. The return statement specifies the value that will be returned.
At a given point, the variables that a statement can access are determined by the scoping rule. The scope of a variable is the section of a program in which the variable can be accessed (also called visible or in scope). There are 2 types of scopes in Java, class scope - a variable defined in a class but not in any method, and block scope (also called a local variable) - a variable defined in a block of a method.
Method overloading is when a class defines multiple methods with the same name. It is usually used to perform the same task on different data types. However, the complier must be able to determine which version of the method is being invoked. This is done by analyzing the parameters, which form the signature of a method which includes the type and order of the parameters.
In object oriented design, methods are grouped together according to objects on which they operate. An object has state, or descriptive characteristics, and behaviors, what it can do (or be done to it). A class contains data declarations and method declarations.