When I am calling a method directly from main method, it is not allowed. However, when I am calling the same method from the constructor of a class, it is allowed.
The allowed version;
public class App {
Integer firstVariable;
Integer secondVariable;
public static void main(String[] args) {
App obj = new App(3, 2);
}
public App(Integer firstVariable, Integer secondVariable) {
this.firstVariable = firstVariable;
this.secondVariable = secondVariable;
this.calculate(firstVariable, secondVariable);
}
public int calculate(int a, int b) {
int result = a + b;
return result;
}
}
The disallowed version;
public class App {
Integer firstVariable;
Integer secondVariable;
public static void main(String[] args) {
App obj = new App(3, 2);
obj.calculate(firstVariable, secondVariable);
}
public App(Integer firstVariable, Integer secondVariable) {
this.firstVariable = firstVariable;
this.secondVariable = secondVariable;
}
public int calculate(int a, int b) {
int result = a + b;
return result;
}
}
I know it is "Cannot make a static reference to the non-static field firstVariable" error. My question is; In both code blocks, the same thing is done but what is the difference between them?