05.0 Java Notes‎ > ‎

Java: Methods

Methods, procedures, functions, subroutines are all basically the same, a chunk of code that does one small task. In Java, each method must be defined in a class.

A method is always followed by a pair of parentheses ().  The parentheses may contain parameters or my be left empty if there are no parameters.

Scope of Methods:
  • private - can not be used outside of the class it is contained in
  • public - can be used by other classes
Return Type
  • void -- no data returned
  •  return data type
Method Parameters 
  • the list in parenthesis including the data type and local name
  • if there are no parameters, the parenthesis are left empty.
Method Signature

Types of methods:
  • setters:  are used to set the value of an instance field. These types of methods are also known as mutators.  A mutator changes (or sets)  the value of a variable.
  • getters:  are used to get the value of an instance field.  Used to allow other objects to get the value of a variable.
  • constructors:  used to create an instance of a object.  
    • must have the same name as the class it constructs
    • the return type is not part of the method header
  • behaviors: methods that make the object take action.  These allow other objects to ask this object to perform an action.  "Tell, don't ask"

Naming a method
  • verb or action phrase that describes the action the method will do