How can I troubleshoot and resolve the issue of “static method cannot be referenced from a non-static context”?

64    Asked by Deepabhawana in Salesforce , Asked on Mar 28, 2024

There is a scenario where in a Java program I have a class “calculator” with a static method “addition” which adds two numbers. Now I am currently creating another class called “MathOperations” where I need to call the “addition” method from the “calculator” class to perform some calculations. However, I am trying to call “calculator.addition(5, 10) from a nonstatic context class, I have encountered the error “static method cannot be referenced from a non-static context”? 

 In the first context of Salesforce, you can troubleshoot and resolve the issue of “static method cannot be referenced from a non-static context” by accessing a static method directly from a non-static context such as from an instance method or constructor. In the context of Java, static methods belong to the class itself rather than to an instance of the class. Therefore, they can be called directly by using the name of the class name without the need for an object instance.



Here is the example given to illustrate this concept:-

Public class Calculator {
    Public static int addition(int a, int b) {
        Return a + b;
    }
}
Public class MathOperations {
    Public void performOperations() {
        // Trying to call a static method from a non-static context
        // This will result in the error “static method cannot be referenced from a non-static context”
        // int result = Calculator.addition(5, 10); // Error line
        // To resolve the error, you can either make the calling method static
        Int resultStatic = Calculator.addition(5, 10);
        // Or create an instance of Calculator and call the static method using the instance
        Calculator calculator = new Calculator();
        Int resultInstance = calculator.addition(5, 10);
        System.out.println(“Result using static call: “ + resultStatic);
        System.out.println(“Result using instance call: “ + resultInstance);
    }
}

Your Answer

Interviews

Parent Categories