------- android培训、java培训、期待与您交流! ----------
自定义一个全静态方法类
class Maths {
public static int add(int x, int y) {
return x + y;
}
public static int sub(int x, int y) {
return x - y;
}
public static int mul(int x, int y) {
return x * y;
}
public static int div(int x, int y) {
return x / y;
}
}
没有静态导入来使用
import cn.mldn.util.Maths;
public class TestDemo {
public static void main(String[] args) throws Exception {
System.out.println("加法操作:" + Maths.add(10, 20));//没有静态导入,要加上类名再调用方法
System.out.println("减法操作:" + Maths.sub(20, 10)); //没有静态导入,要加上类名再调用方法 }}
使用静态导入来使用
import static cn.mldn.util.Maths.*;
public class TestDemo {
public static void main(String[] args) throws Exception {
System.out.println("加法操作:" + add(10, 20));//不需要加上类名,直接调用方法
System.out.println("减法操作:" + sub(20, 10));//不需要加上类名,直接调用方法
}
}
2 可变参数
格式:
public [static][final] 返回值类型 方法名称(参数列表(参数类型...变量)){
return 返回值;
}
可解决同类型不同参数个数的重载方法代码繁琐
(注:可变参数必须放在参数列表的最后。方法体内可将可变参数作为数组变量来使用)
范例
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(add(new int[] { 1, 2, 3 }));
System.out.println(add(1, 2, 3));
System.out.println(add());
}
public static int add(int ... data) { // 可变参数
int sum = 0;
for (int x = 0; x < data.length; x++) {
sum += data[x];
}
return sum;
}
}
3 增强for循环
最早是在.NET中提出来的,是对数组和集合的输出的一种新支持
格式如下:
for(数据类型 数据变量:数组|集合){
...//操作代码
}
这表示通过自动的方式将数组或集合的每一元素赋值给变量,然后在方法体内执行
范例
public class Test {
public static void main(String[] args) throws Exception {
int data[] = new int[] { 1, 2, 3, 4, 5, 6 };
int sum = 0;
for (int x : data) { // 自动循环,将每一个元素赋给x
sum += x;
}
System.out.println(sum);
}
}