谁将成为没有对象的类的方法调用者?

问题描述 投票:0回答:1

在面向对象编程中,“调用者”是指启动/调用另一个对象上的方法或函数的执行的对象或代码。但我的问题是,如果一个类只有方法(静态)而没有对象,那么谁将成为该方法的调用者呢?

我想问的示例代码:

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);
    }
}
java methods static-methods invoke
1个回答
0
投票

在类中可以有两种类型的方法:实例方法和类(或静态)方法。要调用实例方法,您可以使用类的实例(对象)来调用该方法,就像您在示例中所做的那样。要调用类方法,您可以使用类名来调用该方法。

以您为例:

public class Calculator {
public int add(int a, int b) { 
return a + b; 
}
© www.soinside.com 2019 - 2024. All rights reserved.