在面向对象编程中,“调用者”是指启动/调用另一个对象上的方法或函数的执行的对象或代码。但我的问题是,如果一个类只有方法(静态)而没有对象,那么谁将成为该方法的调用者呢?
我想问的示例代码:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
//Creating an instance of the Calculator class
Calculator calc = new Calculator();
// Invoking the "add" method with the invoker (calc)
int result = calc.add(5, 3);
/*
The "calc" object is the invoker, and it invokes the "add" method with arguments
5 and 3.
but what if there was no calc object in the calculator class
who would have been the invoker of the method then?
how would you have then called the add() method? by making it static ?
and calling it directly? if yes, who would be invoker of that static add() method?
*/
System.out.println("Result of addition: " + result);
}
}
在类中可以有两种类型的方法:实例方法和类(或静态)方法。要调用实例方法,您可以使用类的实例(对象)来调用该方法,就像您在示例中所做的那样。要调用类方法,您可以使用类名来调用该方法。
以您为例:
public class Calculator {
public int add(int a, int b) {
return a + b;
}