Java中靜態方法和非靜態方法的調用是有區別的。
①靜態方法可以直接調用,如下冒泡排序,只需將冒泡方法設為static方法即可直接調用。
1 public class BubbleSort { 2 public static void main(String[] args) { 3 int[] a = {6,5,4,3,2,1,23,14,747}; 4 /* 調用bubbleSort方法:直接調用需將bubbleSort設為靜態方法 */ 5 bubbleSort(a); 6 System.out.println(Arrays.toString(a)); 7 } 8 public static void bubbleSort(int[] a) { 9 int temp; 10 for (int i = a.length - 1; i > 0; i--) { 11 for(int j = 0; j < i; j++) { 12 if(a[j] >= a[j+1]) { 13 temp = a[j+1]; 14 a[j+1] = a[j]; 15 a[j] = temp; 16 } 17 } 18 } 19 } 20 }
② 非靜態方法的調用,需要使用對象來調用。還是冒泡排序示例,如下
1 public class BubbleSort { 2 public static void main(String[] args) { 3 int[] a = {6,5,4,3,2,1,23,14,747}; 4 /* 使用對象調用非靜態方法時bubbleSort方法就不需要設為static */ 5 BubbleSort bs = new BubbleSort(); 6 bs.bubbleSort(a); 7 System.out.println(Arrays.toString(a)); 8 9 } 10 public void bubbleSort(int[] a) { 11 int temp; 12 for (int i = a.length - 1; i > 0; i--) { 13 for(int j = 0; j < i; j++) { 14 if(a[j] >= a[j+1]) { 15 temp = a[j+1]; 16 a[j+1] = a[j]; 17 a[j] = temp; 18 } 19 } 20 } 21 } 22 }