メソッドとは、まとまった機能を実現するためのプログラムの書き方です。
メソッドは「入力」を得て、「内部処理」を行い、「出力」を戻します。この入力のことを「引数(ひきすう)」、出力のことを「戻り値(もどりち)」と呼びます。
│ ↓ ┏入力━━━━━━━┓ ┏┫値や参照の型(複数)┣┓ ┃┗━┯━━━━━━━┛┃ ┃ ↓ ┃ ┃┏内部処理━━━━━┓┃ ┃┃ブラックボックス ┃┃ ┃┃自由に行える ┃┃ ┃┗━┯━━━━━━━┛┃ ┃ ↓ ┃ ┃┏出力━━━━━━━┓┃ ┗┫値や参照の型(単一)┣┛ ┗━┯━━━━━━━┛ │ ↓
│ ↓ ┏引数━━━━━━━┓ ┏┫値や参照の型(複数)┣┓ ┃┗━┯━━━━━━━┛┃ ┃ ↓ ┃ ┃┏内部処理━━━━━┓┃ ┃┃ブラックボックス ┃┃ ┃┃自由に行える ┃┃ ┃┗━┯━━━━━━━┛┃ ┃ ↓ ┃ ┃┏戻り値━━━━━━┓┃ ┗┫値や参照の型(単一)┣┛ ┗━┯━━━━━━━┛ │ ↓
メソッドは、以下の基本構造をしています。
戻り値の型 メソッド名(引数の型 変数) { 内部処理 return 戻り値; }
実例を書くと以下のようになります。引数は「(型 変数)」と書き、複数書く場合は「(型 変数, 型 変数, 型 変数)」のように「,」で区切ります。
int plus(int n1, int n2) { int result = n1 + n2; return result; }
上記のコードに説明を加えます。
メソッド名 │ 戻り値の型─┐ │ ┌──引数の型 変数(複数の場合は「,」区切り) │ │ │ int plus(int n1, int n2) { 内部処理 int result = n1 + n2; return result; } └────戻り値
実際にクラスにメソッドを実装して、外部から利用する例を示します。
package sample; public class MyClass { public int plus(int n1, int n2) { int result = n1 + n2; return result; } }
package sample; public class Sample { public static void main(String[] args) { MyClass mc = new MyClass(); int res = mc.plus(1, 2); // 変数resにはplusの戻り値の3が入る System.out.println("res : " + res); } }
res : 3