方法格式详解

  1. 修饰符 返回值类型 方法名(参数列表){
  2. //代码省略...
  3. return 结果;
  4. }
  • 修饰符:
  • 返回值类型: 表示方法运行的结果的数据类型,方法执行后将结果返回到调用者
  • 参数列表:方法在运算过程中的未知数据,调用者调用方法时传递
  • return:将方法执行后的结果带给调用者,方法执行到 return ,整体方法运行结束
  1. public class Test {
  2. public static void main(String[] args) {
  3. int sum = getSum(5,6);
  4. System.out.println(sum);
  5. }
  6. public static int getSum(int a, int b) {
  7. return a + b;
  8. }
  9. }

image.png

方法重载

  • 方法重载:指在同一个类中,允许存在一个以上的同名方法,只要它们的参数列表不同即可,与修饰符和返 回值类型无关。
  • 参数列表:个数不同,数据类型不同,顺序不同。
  • 重载方法调用:JVM通过方法的参数列表,调用不同的方法。
public class Test {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        System.out.println(compare(a,b));
        short c = 245;
        short d = 245;
        System.out.println(compare(c,d));
        int e = 100;
        int f = 100;
        System.out.println(compare(e,f));
    }
    public static boolean compare(byte a, byte b) {
        return a == b;
    }
    public static boolean compare(short a, short b) {
        return a == b;
    }
    public static boolean compare(int a, int b) {
        return a == b;
    }
}