Short answer: make name
static; i.e:
static String name = "asad";
Long answer: You need to understand the difference between static and non-static. static
properties and methods are attached to the class. This means that they are available without an instance of the class, and more importantly, shared between all instances (because they belong to the class itself).
On the other hand, non-static properties and methods belong to the instance of the class only. These are things that belong to a particular instance of the class.
The problem you are facing is that main
is static
. Since main
is invoked on the class itself, it has no idea what name
is, because name
is attached to an instance. Hence name
is undefined in the static context.
Another way, other than making name
static, is to forcibly create an instance of the class and then reference name
that way:
new HelloWorld().name;
But this isn't really good style. You need to think long and hard about what properties/methods need to be static, and which don't. Static properties introduce another wrinkle in the sense that you now have shared state, which can lead to interesting or undesirable behavior if you are not careful.