方法(means)[构造方法]
方法(means)[构造方法]
程序
方法重载
1 public class Method { 2 public static void main(String[] args) { 3 double s = compare(12.34, 65.39); 4 int d = compare(12, 6); 5 System.out.println(compare(1, 21, 21)); 6 System.out.println(s + "\n" + d); 7 } 8 9 //1输出最大数 10 public static double compare(double a, double b) { 11 double max = 0; 12 if (a == b) { 13 System.out.println("a==b"); 14 return 0; 15 } 16 if (a > b) { 17 max = a; 18 } else { 19 max = b; 20 } 21 return max; 22 } 23 24 //2输出最大数 25 public static int compare(int a, int b) { 26 int max = 0; 27 if (a==b) { 28 System.out.println("a==b"); 29 return 0; 30 } 31 if (a>b) { 32 max = a; 33 } 34 else { 35 max = b; 36 } 37 return max; 38 } 39 40 //3输出最大数 41 public static int compare(int a, int b, int c) { 42 int max = a; 43 if(max<b) { 44 max = b; 45 } 46 if(max<c) { 47 max = c; 48 } 49 return max; 50 } 51 }
要点
-
定义
在一个类中有相同的函数名称,但形参不同的函数。
-
规则
方法名称相同。
参数列表必须不同(个数、类型、参数排列顺序等)。
仅仅返回类型不同不足以成为方法的重载。
-
实现理论
方法名称相同时,编译器会根据调用方法的参数个数、参数类型等去逐个匹配,以选择对应的方法,如果匹配失败报错。
可变参数(type ... var)
1 public class Method { 2 public static void main(String[] args) { 3 Method m = new Method(); 4 m.add(12,32,34,45,65,6); 5 System.out.println(); 6 System.out.println(m.adb(1,23,35,56,543,2,45,7,34)); 7 8 } 9 public void add(int... a) { 10 for (int i=0; i<a.length; i++) 11 System.out.print(a[i] + "\t"); 12 } 13 //可变参数传的就是一个数组 14 public int adb(int... a) { 15 int result = 0; 16 for (int i=0; i<a.length; i++) 17 if (result < a[i]) 18 result = a[i]; 19 return result; 20 } 21 //可变参数必须放在最后 22 public void add(double a, int b, int... c) { 23 } 24 }
静态匿名代码块、匿名代码块、构造器
1 //静态导入包 2 import static java.lang.Math.*; 3 public class Static { 4 //1 程序运行中只执行一次,不管创建多少对象 5 static { 6 System.out.println("静态匿名代码块"); 7 } 8 //2 在构造器之前静态代码块之后,每次创建对象都执行 9 //可以用来赋初始值 10 { 11 System.out.println("匿名代码块"); 12 } 13 //3 14 public Static() 15 { 16 System.out.println("构造器"); 17 } 18 public static void main(String[] args) { 19 Static a = new Static(); 20 System.out.println("==========="); 21 Static b = new Static(); 22 //随机生成小于1的数 23 System.out.println(random()); 24 } 25 }

浙公网安备 33010602011771号