Method
A method is a function declared inside a class. It determines the behavior of the object, i.e. what actions it can perform.
The methods are described as follows (all described methods have the “public” access modifier):
static double norm(double[] vector)
where:
• static - indicates that the method is static (applies to the class). If not specified, the method is considered non-static (applies to an object of the class).
• double - the data type returned by the method. If not specified, the method is considered to return nothing ("void").
• norm - the method name.
• double[] vector - the name of the argument accepted by the method (vector), and its data type/class (double[]). If not specified, the method is considered to accept no input parameters.
Basic rules for declaring a method in java:
May contain an access modifier. There are several such modifiers, but when creating custom code methods for models, only the “public” access modifier is used (indicating that the declared method is accessible from anywhere: from any class in any package).
May contain other modifiers (for example, static - an indication that the method belongs to the class and not to an object of the class).
Must contain the type/class of the return value. If the method does not return anything, then “void” is specified.
The “return” keyword is used to indicate what exactly the method returns (unless “void” is specified).
It must contain parentheses, inside which the parameters that the method takes as input are listed. If the method does not accept anything as input, then () is specified.
An example of declaring a method that returns something inside a class:
// Circle class
public class Circle {
// Class fields:
// radius - circle radius (double data type)
private double radius;
// Method that returns the circle area
public double getArea() {
double area = Math.PI * square(radius);
return area;
}
}
An example of declaring a method that does not return anything inside a class:
// Circle class
public class Circle {
// Class fields:
// radius - circle radius (double data type)
private double radius;
// Method that returns nothing. It simply prints information about the circle area
public void printArea() {
double area = Math.PI * square(radius);
System.out.println("Circle area: " + area);
}
}
Methods can be static (the “static” modifier is specified when declaring them; such methods apply to the entire class, and not to specific objects of this class) and non-static (they refer to specific objects of the class).
A static method is accessed through the name of the class itself, for example:
Cell.createCell(CellDefinition cd, Model model, double[] position);
• Cell - the class name.
A non-static method is accessed through the name of an object of a class, for example:
Cell cell1 = new Cell(CellDefinition cd, Model model);
сell1.getMicroenvironment();