Java中静态方法和非静态方法的调用

时间:2023-02-13 13:03:41

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 }