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..