public class MethodOverload {
public static void main(String[] args) {
System.out.println("The square of integer 7 is " + square(7));
System.out.println("\nThe square of double 7.5 is " + square(7.5));
}
public static int square(int x) {return x * x;
}public static double square(double y) {return y * y;
}
}
The square of integer 7 is 49
The square of double 7.5 is 56.25
这段代码演示了 Java 中的方法重载机制。
编译器根据传入参数的类型自动选择对应的方法。
重载允许同一方法名处理不同类型的数据,提高代码的可读性和复用性。