方法的是什麼:java
方法的格式:設計
方法的設計:code
程序代碼以下:遞歸
public class Method { public static void main(String[] args) { System.out.print("直接輸出:"); //直接輸出 System.out.println("input"); System.out.print("無參無返回:"); //無參無返回 Method.Meth1(); System.out.print("無參有返回:"); //無參有返回 System.out.println(Method.Meth2()); System.out.print("有參無返回:"); //有參無返回 Method.Meth3("Hello"); System.out.print("有參有返回:"); //有參有返回 System.out.println("1+2=" + Method.Meth4(1, 2)); } //無參無返回方法 static void Meth1(){ System.out.println("input meth1"); } //無參有返回參數 static int Meth2(){ return 2; } //有參無返回 static void Meth3(String para){ System.out.println(para); } //有參有返回 static int Meth4(int a, int b){ return a+b; } }
運行結果:input
直接輸出:input 無參無返回:input meth1 無參有返回:2 有參無返回:Hello 有參有返回:1+2=3
方法的重載:在同一個類中,同名不一樣參的方法。class
* 兩同:同一個類,同一個方法名。
* 一不通:方法參數列表不一樣(參數類型、個數、順序)程序
程序代碼以下:方法
public class OverLoad { public static void main(String[] args) { System.out.println(sun(1, 2)); System.out.println(sun(1, 2, 3)); System.out.println(sun(1.1, 2.3)); System.out.println(sun(1, 2.3)); sun(); sun(1); } static int sun(int a, int b){ return a+b; } static double sun(double a, double b){ return a+b; } static int sun(int a, int b, int c){ return a+b+c; } static void sun(){ System.out.println("a"); } static void sun(int a){ System.out.println(a); } }
運行結果:im
3 6 3.4 3.3 a 1
方法的遞歸操做:在同一個類中,同名不一樣參的方法。static