Home > front end >  Who will be the method invoker of a Class with no object?
Who will be the method invoker of a Class with no object?

Time:11-05

In object-oriented programming, an "invoker" refers to an object or code that initiates/invokes the execution of a method or function on another object. But my question is what if a class has just methods(static) and no object who will then be the invoker of that method?

Example Code of what I am trying to ask :

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);
    }
}

CodePudding user response:

In a class there could be two types of methods: instance methods and class (or static) methods. To call an instance method you use an instance (object) of the class to invoke the method, like you did in your example. To call a class method you use the class name to invoke the method.

Taking your example:

public class Calculator {
  public static int add(int a, int b) { 
    return a   b;
  } 
}
    
public static void main(String[] args) { 
  System.out.println(Calculator.add(5,3));
}

Method add is declared as static and we call it using the class name Calculator.

In the Calculator class there is no state, there are no attributes. Usually a class with no state will have only static methods since the behaviour of the method does not depend on any state.

  • Related