从另一个 class 调用静态方法而不在 Java 中创建对象
Call static method from another class without creating object in Java
我们能否在不创建定义静态方法的 class 的对象的情况下,在另一个 class 中访问一个 class 中定义的静态方法?
class Test{
public static int add(int a, int b){
return a+b;
}
}
public class Methods{
public static void main(String[] args){
System.out.println("The sum of 2 and 3 is: " + add(2,3));
}
}
在此代码片段中,当我尝试从 Methods
class 调用 Test
class 中定义的 add
方法时,我得到以下错误:
Methods.java:12: error: cannot find symbol
System.out.println("The sum of 2 and 3 is: " + add(2,3));
^
symbol: method add(int,int)
location: class Methods
1 error
但是当我尝试使用 Methods
中的 Test
方法的对象调用静态方法时,它工作正常!
而不是做
add(2,3)
做
Test.add(2,3)
创建静态方法的全部意义在于访问它而不创建 class 的实例。但是需要引用 class 名称,因为您正在其中定义方法。因此,在您的情况下,您需要 Test.add(a,b),其中 Test 是 class 的名称而不是它的实例。
我们能否在不创建定义静态方法的 class 的对象的情况下,在另一个 class 中访问一个 class 中定义的静态方法?
class Test{
public static int add(int a, int b){
return a+b;
}
}
public class Methods{
public static void main(String[] args){
System.out.println("The sum of 2 and 3 is: " + add(2,3));
}
}
在此代码片段中,当我尝试从 Methods
class 调用 Test
class 中定义的 add
方法时,我得到以下错误:
Methods.java:12: error: cannot find symbol
System.out.println("The sum of 2 and 3 is: " + add(2,3));
^
symbol: method add(int,int)
location: class Methods
1 error
但是当我尝试使用 Methods
中的 Test
方法的对象调用静态方法时,它工作正常!
而不是做
add(2,3)
做
Test.add(2,3)
创建静态方法的全部意义在于访问它而不创建 class 的实例。但是需要引用 class 名称,因为您正在其中定义方法。因此,在您的情况下,您需要 Test.add(a,b),其中 Test 是 class 的名称而不是它的实例。