【发布时间】:2021-09-25 18:24:30
【问题描述】:
我们是否可以在不创建定义静态方法的类的对象的情况下访问另一个类中一个类中定义的静态方法?
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));
}
}
在这段代码 sn-p 中,当我尝试从 Methods 类中调用 Test 类中定义的 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 方法的对象调用静态方法时,它工作正常!
【问题讨论】:
-
Test.add(2,3)? -
“使用Test方法的对象”是什么意思?
-
我认为他的意思是这种可憎的东西:
new Test().add(2, 3);
标签: java class oop methods static