2016-03-15 41 views
0

我想调用这个方法:调用方法的Java

public int ArraySum(int[] a) 
    { 
     int sum = 0; 
     int Element; 
     for(Element = 0; Element < a.length; Element++) 
     { 
      sum = sum + a[Element]; 
     } 
     return sum; 
    } 

在这种方法(在不同的类):

public int Mean() 
    { 
     return (something.ArraySum(a))/2; 
    } 

我知道,我可能需要创建一个对象但我不确定如何。

+0

因为该方法ISN” t静态,你需要一个封闭类的实例。你还没有发布。此外,Java方法名称应以小写字母开头。 –

+1

您可能想使用'/ a.length'而不是'/ 2'。 –

+0

Elliott Frisch,请你详细说明一下吗?当你说封闭课程或我需要该课程的一个实例时,我不确定你的意思。 – Alioune

回答

0

只是一个例子:

public class C1 
{ 
    //all the fields and stuff 
    public int hello(int a) 
{ 
    //all the code 
} 
    public static int hey(int a) 
    { 
    //all code 
} 
} 

注:上述功能之一是静态的。观察我们如何称呼他们。

public class C2 
{ 
//all fields and stuff 
public void callerFunction() 
{ 
    C1 obj=new C1(); 
    //created an object of class C1 
    obj.hello(5); 
    C1.hey(10); 
    //only class name is required while calling static methods. 
} 
} 
+0

所以你说对象需要调用方法? – Alioune

+0

如果该方法不是静态的,那么您需要一个对象来调用它。因为每个对象都有单独的方法副本,而静态方法是类方法,并且对于所有对象都是唯一的。 –

0

您需要创建类ArraySum方法所在的对象。如果它出现在Calculator类象下面这样:

public class Calculator{ 
    public int ArraySum(int[] a){ 
     int sum = 0; 
     int Element; 
     for(Element = 0; Element < a.length; Element++) 
     { 
      sum = sum + a[Element]; 
     } 
     return sum; 
    } 
} 

然后,你需要做的是(假设类没有定​​义任何非零参数的构造函数)是什么,

Calculator calculator = new Calculator(); 
calculator.ArraySum(..);