面向对象(9-1):制作工具类
面向对象(9):制作工具类
1、例:遍历数组、输出数组元素中的最大值
public class ArrayDemo {
public static void main(String[] args) {
//定义一个数组
int[] arr = {12,27,36,68,34,72,88};
//遍历数组
for(int i =0;i<arr.length;i++){
if(i==arr.length-1){
System.out.print(arr[i]+"]");
} else if(i==0){
System.out.print("["+arr[i]+",");
}else{
System.out.print(arr[i]+",");
}
}
System.out.println();
//需求:输出数组中的最大值
int max = arr[0];
for(int i =0;i<arr.length;i++){
if(arr[i]>max){
max = arr[i];
}
}
System.out.println("数组中的最大值为:"+max);
}
}
执行结果为:
[12,27,36,68,34,72,88]
数组中的最大值为:88
Process finished with exit code 0
将来如果代码中有很多地方都需要遍历数组、求数组最值、逆序等等,都要再写一遍一样的代码,特别麻烦;
那么我们将每一个功能封装成一个方法,将这些对数组操作的方法全部存储在一个ArrayTool类(工具类)中,以后需要操作数组的时候,直接调用出来。
自定义一个类,命名为ArrayTool,在里面将需要的方法编写进去
2、例:遍历数组、输出数组元素中的最大值
创建工具类对象,然后通过对象调用方法
public class ArrayDemo {
public static void main(String[] args) {
//定义一个数组
int[] arr = {12, 27, 36, 68, 34, 72, 88};
//遍历数组
//第1步:创建工具类对象(快捷键:new ArrayTool.var回车)
ArrayTool arrayTool = new ArrayTool();
//第2步:调用工具类中遍历方法
arrayTool.printArray(arr);//对象名.方法名(数组名)
System.out.println();//表示换行
//输出数组元素中的最大值
//第1步:创建工具类对象(快捷键:new ArrayTool.var回车)
ArrayTool arrayTool1 = new ArrayTool();
//调用工具类中求最大值的方法
//因为有返回值,所有调用方法后,需要接收一下
int max = arrayTool1.getMaxNum(arr);//对象名.方法名(数组名)
System.out.println("数组中元素的最大值为:"+max);
}
}
执行结果为:
[12,27,36,68,34,72,88]
数组中的最大值为:88
Process finished with exit code 0
也可以通过工具类名直接调用方法,更为简洁
public class ArrayDemo {
public static void main(String[] args) {
//定义一个数组
int[] arr = {12, 27, 36, 68, 34, 72, 88};
//遍历数组
//通过工具类名直接调用方法
ArrayTool.printArray(arr);
System.out.println();//表示换行
//输出数组元素中的最大值
int max = ArrayTool.getMaxNum(arr);
System.out.println("数组中元素的最大值为:"+max);
}
}
执行结果为:
[12,27,36,68,34,72,88]
数组中的最大值为:88
Process finished with exit code 0 a
3、当我们创建的工具类中的方法,不想让别的程序随意创建工具对象来调取,
我们可以将工具类中的构造方法私有化,私有化后的工具类中的方法,
只能通过工具类名来调换,不能创建对象来调取方法。
私有化如下:
public class ArrayTool {
private ArrayTool(){ //将构造方法私有化(加private)
}
//遍历数组的方法
public static void printArray(int[] array){
for(int i =0;i<array.length;i++){
if(i==array.length-1){
System.out.print(array[i]+"]");
} else if(i==0){
System.out.print("["+array[i]+",");
}else{
System.out.print(array[i]+",");
}
}
}
.......
.......
私有化后,只能通过工具类类名来调取内部的方法
格式 工具类名.方法名(数组名);
调取方法如下:
........
ArrayTool.printArray(arr);//无返回值调取
int max = ArrayTool.getMaxNum(arr);//因为有返回值,所有调用方法后,需要接收一下
System.out.println("数组中元素的最大值为:"+max);
.........
.........

浙公网安备 33010602011771号