java - Non-static variable cannot be referenced from a static context -


i've written test code:

class myprogram {     int count = 0;     public static void main(string[] args)     {         system.out.println(count);     } } 

but gives following error:

main.java:6: error: non-static variable count cannot referenced static context         system.out.println(count);                            ^ 

how methods recognize class variables?

you must understand difference between class , instance of class. if see car on street, know it's car if can't see model or type. because compare see class "car". class contains similar cars. think of template or idea.

at same time, car see instance of class "car" since has properties expect: there driving it, has engine, wheels.

so class says "all cars have color" , instance says "this specific car red".

in oo world, define class , inside class, define field of type color. when class instantiated (when create specific instance), memory reserved color , can give specific instance color. since these attributes specific, non-static.

static fields , methods shared instances. values specific class , not specific instance. methods, global helper methods (like integer.parseint()). fields, it's constants (like car types, i.e. have limited set doesn't change often).

to solve problem, need instantiate instance (create object) of class runtime can reserve memory instance (otherwise, different instances overwrite each other don't want).

in case, try code starting block:

public static void main (string[] args) {     try     {         myprogram7 obj = new myprogram7 ();         obj.run (args);     }     catch (exception e)     {         e.printstacktrace ();     } }  // instance variables here  public void run (string[] args) throws exception {     // put code here } 

the new main() method creates instance of class contains (sounds strange since main() created class instead of instance, can this) , calls instance method (run()).


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -