2015-10-20 95 views
-3

我知道這個話題有很多問題。 我有兩個過程叫做arrPrint方法。什麼是從Java中的靜態方法調用非靜態方法的最佳方式?

第一個步驟:

public class Test { 
    public static void main(String args[]) { 
    int[] arr = new int[5]; 
    arr = new int[] { 1, 2, 3, 4, 5 }; 

    Test test = new Test(); 
    test.arrPrint(arr); 

} 

public void arrPrint(int[] arr) { 
    for (int i = 0; i < arr.length; i++) 
     System.out.println(arr[i]); 

    } 
} 

第二步驟:

public class Test { 
    public static void main(String args[]) { 
    int[] arr = new int[5]; 
    arr = new int[] { 1, 2, 3, 4, 5 };  
    arrPrint(arr); 
} 

public static void arrPrint(int[] arr) { 
    for (int i = 0; i < arr.length; i++) 
    System.out.println(arr[i]); 
    } 
} 

哪個程序是最好的,爲什麼?

+0

爲什麼你需要很多方法來調用實例方法?問問哪一個更好? :) –

回答

0

實例方法在一個類的實例上運行,因此要執行一個實例方法需要一個類的實例。因此,如果您想從靜態方法中調用實例方法,則需要對實例進行一些訪問,無論是全局變量還是作爲參數傳遞。否則,您將收到編譯錯誤。

0

「實例方法」表示該方法需要在類的實例上執行。對象的關鍵在於實例可以擁有自己的專用數據,實例方法所執行的數據,所以嘗試在沒有對象實例的情況下調用實例方法是沒有意義的。如果你改寫你的例子:

public class Test { 

    int[] arr = new int[] {1,2,3,4,5}; 

    public static void main(String args[]) { 
     Test test = new Test(); 
     test.arrPrint(); 
    } 

    public void arrPrint() { 
     for (int i = 0; i < arr.length; i++) 
      System.out.println(arr[i]); 
    } 
} 

然後這變得有點簡單了。 Test的實例擁有自己的數據,實例方法可以訪問並執行某些操作。

看看像String或ArrayList這樣的JDK類,看看它們是如何設計的。它們封裝數據並允許通過實例方法訪問數據。

0

如果您想在另一個類中使用方法arrPrint,則使用第二個過程。

public class A{ 
    public int[] intArray; 

    public A(int[] intArray) { 
     this.intArray = intArray; 
    } 

    public int[] getIntArray() { 
     return intArray; 
    }   
} 


public class Pourtest { 
    public static void main(String args[]) { 
    int[] arr = new int[5]; 
    arr = new int[] { 1, 2, 3, 4, 5 }; 
    A a = new A(arr); 
    arrPrint(a.getIntArray()); 
} 

    public static void arrPrint(int[] arr) { 
     for (int i = 0; i < arr.length; i++)System.out.println(arr[i]); 
    } 
} 
相關問題