调用Java方法
我想调用此方法:调用Java方法,java,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 ArraySum(int[] a)
{
int sum = 0;
int Element;
for(Element = 0; Element < a.length; Element++)
{
sum = sum + a[Element];
}
return sum;
}
我知道我可能需要创建一个对象,但我不确定具体如何创建。举个例子:
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.
}
}
您需要创建中存在的类
ArraySum
方法的对象。例如,如果它出现在计算器
类中,如下所示:
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;
}
}
因为该方法不是静态的,所以需要一个封闭类的实例。你还没有发布。此外,Java方法名称应以小写字母开头。您可能希望使用
/a.length
而不是/2
。Elliott Frisch,您能详细说明一下吗?我不确定你所说的封闭类是什么意思,或者我需要该类的实例。那么你是说需要对象来调用方法?如果方法不是静态的,那么你需要对象来调用它。因为每个对象都有一个单独的方法副本,而静态方法是类方法,并且对于所有对象都是唯一的。
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(..);