-5

I'm a beginner and I'm starting to learn programming by doing some exercises... Why this simple java code gives me an error?

class HelloWorldEdited {
    public int a = 5;
    public int b = 2;

    public static int sum() {
        return a + b;
    }

    public static void main(String[] args) {
        HelloWorldEdited obj = new HelloWorldEdited();

        System.out.println(obj.sum());
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
boorat
  • 63
  • 1
  • 3
  • 6
    What error are you getting? Make sure to include all the relevant info when asking a question, otherwise people will be less inclined to answer your question. See [How to Ask](http://stackoverflow.com/help/how-to-ask) for more info. – Mage Xy Jan 19 '16 at 19:39
  • The first step in diagnosing and correcting an error is *always* reading the error message... – David Jan 19 '16 at 19:46
  • changing "public static int sum()" to "public int sum()" solve the problem, thank you for the advices. I'm going to read "how to ask" – boorat Jan 19 '16 at 19:46
  • `static` members belongs to "class" non-static members belong to instances. Lets say that you have many instances, like `new HelloWorldEdited(1,2);` and `new HelloWorldEdited(3,4);` which values `a` and `b` should be used when you call `HelloWorldEdited.sum()`? ... Compiler also don't know which is why it is forbidden in Java. – Pshemo Jan 19 '16 at 19:46

2 Answers2

6

I think it's because you are accessing "non static" properties (a, b) from a static method (sum), this operation is forbidden.

Try to change

public static int sum()

to

public int sum()

To understand the "static" modifier I suggest you to read: official tutorial

Pshemo
  • 122,468
  • 25
  • 185
  • 269
An0nym0u5
  • 26
  • 4
0

The method sum() is static. In this method you can't access variables "non static".