-3

I have a class Program. Here it has main method.It is static method. I created a simple getAllSum method to return sum of three values.But, if i remove static keyword then i get error as:

**Cannot make a static reference to the non-static method getALlsum(int, int, int) from the type Program
**

If I am calling a function from static method to non static method then,why it is necessary to become non static method to be static?

Static method I have learned about them is that:

  1. Can be called from class name instead of using object.
  2. Each object shares the same variable.

But,I am getting confuse why cant we call a nonstatic function from static function?What is the reason behind this?

public class Program {

    public static void main(String[] args) {
        int l=getALlsum(1,2,3);
        System.out.println(l);
    }

    public static int getAllSum(int a,int b,int c) {
        return (a+b+c);
    }

    }
Random guy
  • 883
  • 3
  • 11
  • 32
  • 1
    `static` = one per class, not `static` = one per instance. If you are in a `static` method, then there is no instance of the class to invoke your methods on. `new Program(). getAllSum(1,2,3);` – Elliott Frisch Mar 15 '20 at 13:28
  • 1
    Separately, just FWIW, *"Why cant we call nonstatic method from static method?"* You **can**, in situations where it's appropriate: You create an instance, then call the method on it. – T.J. Crowder Mar 15 '20 at 13:29

1 Answers1

-1

You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.

You need to make an instance of your class, and call your method

Mahesh Anakali
  • 344
  • 1
  • 8