宝安公司网站制作哪家公司好,西安电子商务网站,公司网络优化方案,海口注册公司流程及费用文章目录 6.5 方法的重载6.6 方法练习数组遍历数组最大值 6.5 方法的重载
在 Java 中#xff0c;方法的重载是指在同一个类中定义多个方法#xff0c;这些方法具有相同的名称#xff0c;但参数列表不同。方法的重载是一种实现多态的方式#xff0c;允许一个方法名以不同的… 文章目录 6.5 方法的重载6.6 方法练习数组遍历数组最大值 6.5 方法的重载
在 Java 中方法的重载是指在同一个类中定义多个方法这些方法具有相同的名称但参数列表不同。方法的重载是一种实现多态的方式允许一个方法名以不同的方式工作。
方法重载的规则
参数的个数不同 例如一个方法有两个参数另一个方法有三个参数。参数的类型不同 例如一个方法接收 int 类型参数另一个方法接收 double 类型参数。参数的顺序不同仅在参数类型不同的情况下 例如一个方法参数顺序是 (int, double)另一个方法是 (double, int)。
示例代码
package MethodDemo;/*** Author: wang* Create: 2025/1/24* Description: 方法重载**/
public class MethodOverloadingExample {// 方法1接收两个 int 类型参数public void display(int a, int b) {System.out.println(Two integers: a , b);}// 方法2接收一个 double 类型参数public void display(double a) {System.out.println(One double: a);}// 方法3接收一个 int 和一个 double 类型参数public void display(int a, double b) {System.out.println(One integer and one double: a , b);}// 方法4接收一个 double 和一个 int 类型参数public void display(double a, int b) {System.out.println(One double and one integer: a , b);}public static void main(String[] args) {MethodOverloadingExample example new MethodOverloadingExample();example.display(10, 20); // 调用方法1example.display(5.5); // 调用方法2example.display(10, 5.5); // 调用方法3example.display(5.5, 10); // 调用方法4}
}打印结果 需求使用方法重载的思想设计比较两个整数是否相同的方法 6.6 方法练习
数组遍历
需求设计一个方法用于数组遍历要求遍历的结果是在一行输出例如[11, 22, 33, 44, 55]。
示例代码
package MethodDemo;/*** Author: wang* Create: 2025/1/27**/
public class Example1 {public static void main(String[] args) {// 定义数组int[] arr {11, 22, 33, 44, 55};// 调用方法遍历数组printArray(arr);}// 定义用于数组的遍历public static void printArray(int[] arr) {System.out.print([);for (int i0; iarr.length; i) {if(i arr.length - 1){System.out.print(arr[i]);}else{System.out.print(arr[i] , );}}System.out.println(]);}
}运行结果 数组最大值
需求定义一个数组求数组最大值。
示例代码
package MethodDemo;/*** Author: wang* Create: 2025/1/27**/
public class Example2 {public static void main(String[] args) {// 定义数组int[] arr {1, 5, 7, 35, 2};// 调用方法int max getMax(arr);System.out.println(max);}// 定义求数组最大值的方法public static int getMax(int[] arr) {int max arr[0];for (int i 1; i arr.length; i) {if (arr[i] max) {max arr[i];}}return max;}
}运行结果