在java中从静态方法调用非静态方法的最佳方法是什么?

时间:2015-10-20 13:36:45

标签: java static

我知道有很多关于这个话题的问题。 我有两个程序来调用arrPrint方法。

第一程序:

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]);
  }
}

哪种程序最好,为什么?

3 个答案:

答案 0 :(得分:0)

实例方法在类的实例上运行,因此要执行实例方法,您需要一个类的实例。因此,如果要从静态方法中调用实例方法,则需要对实例进行一些访问,可以是全局变量,也可以作为参数传递。否则,您将收到编译错误。

答案 1 :(得分: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类,看看它们是如何设计的。它们封装数据并允许通过实例方法访问它。

另一方面,静态方法无法查看实例数据,因为它们不属于对象实例。如果实例方法不接触任何实例数据,则某些静态分析工具(如sonarqube)会建议将实例方法更改为静态方法。由于您的方法对传入的数据进行操作,并且创建的对象无需将其作为实例方法调用,因此最好将其作为静态方法。

答案 2 :(得分: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]);
    }
}
相关问题