【问题标题】:What is the best way to called non-static method from static method in java?从java中的静态方法调用非静态方法的最佳方法是什么?
【发布时间】:2015-10-20 13:36:45
【问题描述】:

我知道有很多关于这个话题的问题。 我有两个过程调用 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]);
  }
}

哪种方法最好,为什么?

【问题讨论】:

  • 为什么需要大量的方法来调用实例方法?想问哪个好? :)

标签: java static


【解决方案1】:

实例方法在类的实例上运行,因此要执行实例方法,您需要一个类的实例。因此,如果您想从静态方法中调用实例方法,则需要对实例进行一些访问,无论是全局变量还是作为参数传递。否则会出现编译错误。

【讨论】:

    【解决方案2】:

    如果您想在另一个类中使用方法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]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      “实例方法”表示该方法需要在类的实例上执行。对象的重点是实例可以拥有自己的专用数据,实例方法会根据这些数据进行操作,因此尝试在没有对象实例的情况下调用实例方法是没有意义的。如果您将示例重写为:

      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 会建议将实例方法更改为静态方法。由于您的方法对传入的数据进行操作,并且创建将其作为实例方法调用的对象是不必要的,因此它最好是静态方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-04
        相关资源
        最近更新 更多