2013年12月6日 星期五

java-variable

java-static-variable java-variable-static

instance Variables

Instance variables are defined inside the class, but outside of any method, and are only initialized when the class is instantiated. Instance variables are the fields that belong to each unique object .


Static Variables

In contract, there is only a copy of static variables for all objects of a class. Since this copy of static variables is independent of the objects, hence the static variables are also known as class variables. Java allocates memory space for the static variables the first time it encounters the class.

In a class, you cannot define an instance variable and a static variable using the same name.

e.g.
class car {
static int noofawards = 0;
 }

car.noofawards or car1.noofawards or car2.noofawards are actually referencing the same static variable.

Local Variables
Local variables are used internally inside a block. e.g. methods do-while statements ... etc, enclosed by "{ }".These local variables cannot be referenced externally.




java non static cannot referenced static context


inf : http://stackoverflow.com/questions/4922145/non-static-method-cannot-be-referenced-from-a-static-context-error

inf : http://stackoverflow.com/questions/4922145/non-static-method-cannot-be-referenced-from-a-static-context-error

a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined name as static variable.Now no matter how many student object you create all will have same name.

Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.
b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.

Object Level: They will get initialized when you create a new object ,say by new();
C)
Your Problem : Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.

Now from that you want to call an Object varibale : Where is the object ??
You have to create a Object and then only you can access Object level varibales.


In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.
"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.

沒有留言:

張貼留言