赞
踩
实现同一个函数名,不同参数个数,实现的方法相同
法一:函数重载
- public class VaiParameter01 {
- public static void main(String[]args){
- Methods m= new Methods();
- System.out.println(m.sum(1,5,100));
- System.out.println(m.sum(1,5,100,55));
- }
- }
- class Methods{
- //计算2/3/4个数的和
- //可以使用方法重载
- public int sum(int n1,int n2,int n3){
- return n1+n2+n3;
- }
- public int sum(int n1,int n2,int n3,int 4){
- return n1+n2+n3+n4;
- }
-
- }

法二:可变参数优化
Java中的可变参数(Variable Arguments)允许在方法中定义一个参数列表,使得该方法可以接受任意数量的相同类型的参数。在方法声明中使用三个点(...)来表示可变参数的占位符,并且该占位符可以接受任意数量的相同类型的参数。
eg1:
- public class VaiParameter01 {
- public static void main(String[]args){
- Methods m= new Methods();
- System.out.println(m.sum(1,5,100));
-
- }
- }
- class Methods{
- //使用可变参数优化
- //1.int... 接受的是可变参数,类型是int ,即可接收多个int(0-多)
- //2.使用可变参数时,可以当作数组来使用,把nums看作数组
- //3.遍历nums求和即可
- public int sum(int...nums){
- //System.out.println("接受的参数的个数="+nums.length);
- int res=0;
- for(int i=0;i<nums.length;i++){
- res+=nums[i];
- }
- return res;
- }
- }

eg2:
- public class VarParametersExercise {
- public static void main(String[]args){
- Method methods= new Method();
- System.out.println( methods.showScore("xiaomin",90,45.56,32,12,45,75));
- }
- }
- class Method{
- public String showScore(String name,double...score){
- double totalscore=0;
- for(int i=0;i<score.length;i++){
- totalscore+=score[i];
- }
- return name+" score="+totalscore;
- }
- }
-

注意事项:
1.可变参数可以时一个数组
2.可变参数可有0或多个
3.可变参数可以和普通类型一起放在形参列表,但是必须放在最后
4.一个形参列表最多只能出现一个可变参数
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。