0

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?

Bernhard Colby
  • 311
  • 5
  • 17

1 Answers1

1

The issue isn't your method. The issue is that your variables (the arguments that you're trying to pass) are being referenced from a static context.

yngwietiger
  • 1,044
  • 1
  • 11
  • 15
  • Why the downvote? What I say is true. It's not the method, it's the arguments he's trying to pass that are the problem. I even pulled the code up in IntelliJ, and that's what it's complaining about. – yngwietiger Dec 25 '15 at 19:03
  • I didn't downvote, but the problem is actually that the variables _are not_ static, which is why you can't use them in `main`. – Mick Mnemonic Dec 25 '15 at 19:04
  • Right. I fixed my comment. What I meant is that he's trying to reference them from a static context. – yngwietiger Dec 25 '15 at 19:05