0

I'm studying about static and methods now.. and I have some questions about these..

So, I tried this one first

class Calculator{
    int addNumbers(int a,int b){
        return a+b;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Calculator.addNumbers(1,23));
    }
}

And I got this error message

Error:(11, 38) java: non-static method addNumbers(int,int) cannot be referenced from a static context

So, I searched and people said I should call the method in an instance like below and it worked..

class Calculator{
    int addNumbers(int a,int b){
        return a+b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        System.out.println(calculator.addNumbers(1,23));
    }
}

I'm wondering why I can't use the non static method without using instance.. Why do class methods have to be used with instance? Is it just the rule??
So far I just feel like since main() method is static everything in other class should be static to be used in main method..

  • 2
    If you want your method to be called without an instance, make it a static method. That is exactly what static method *means* in Java. – khelwood Jun 28 '20 at 21:17
  • re: *Why do class methods have to be used with instance?* A non-static method **belongs** to a single instance and therefore you need an instance on which to call the method. For a non-programming analogy, consider the class of people and the attribute of height. You can only determine the height **of** a **particular** person, not the height of some definition of personhood. – user13784117 Jun 29 '20 at 02:30

0 Answers0