Java summary: Methods

Declaration syntax

[abstract][access] [static][final] [return-type] name( [parameters] ) { body: implementation }

Method without an implementation. Member of an abstract class or interface.
access If no scope is given, a method has package scope. public: everyone can see it, protected: subclasses can use it and private: can only be seen from within this class.
static The static keyword is used to declare class methods -- methods that don't refer to a specific object. Call it with a class specifier: Class.Method(). Eg. Math.cos(x) calls the static cosine method in the Math class
return-type Any type (including classes & arrays). Use void if the method doesn't return a value.
Cannot be overridden by a child class.

Method signature

The signature (or header) of a method consists of its name and the parameter types. Each method of a class should be different in its signature. It is used to select the method that has to be called.

Overloading (polymorphism)

A method is overloaded when there are two or more methods by the same name in a class.


You can override a method in a child class, by defining a method with the same signature as a method in the parent class. All calls will go to your new method. To call the method in the parent class, you must prefix the call with super..

Method Body

Objects and arrays as parameter are always passed by reference
Variables that you declare in a method are called local variables. You must assign a value before using them. They are created on a call stack when the method is entered, and they are destroyed when the method returns. Because objects (eg. Strings and arrays) are allocated in the heap (with new), they are never in the call stack and can be returned from the method.
Use the
return statement to give the return value of a method. If a method does not return a value, there is no need for a return statement.

Special Methods

   public static void main(String[] args){..}