Originally posted by Sean Lee:
Maybe I'm not very familiar with these two concepts: class and instance. In my opinion, the class is the definition of a object, and the instance is a implementation of the object, isn't it?
Yes, that's pretty much correct. You realize you can make as many instances of a class as you want right? In this respect, a class is sort of like a cookie-cutter template that can create a bunch of the same type of object.
i'm really comfused with these. expecailly with those two terms: class variable and instance variable. please help me to make it clear. thanks.
An instance variable (actuall both variables and methods) belongs to a single instance of a class. If I have a class Person:
class Person{
String name; }
Each instance of the Person class will have it's own copy of this variable. That way, each object can maintain a unique value for it. One object can have a name="Bob", and another "Fred."
A class variable is shared by ALL the objects of a class. If I add a class variable to the Person class above:
class Person{
static int numberOfPeople; //class variable
String name; //instance variable
}
First you notice we use the keyword "static" to indicate it's a class variable.
Now, each object shares the variable named numberOfPeople. If one object were to change the value, that change would be visible to ALL Objects of type Person. You could use this particular variable to keep track of how many Person objects had been created.
Class variables have many uses, but the key point is that EVERY object of that class SHARES a single class variable, whereas EVERY object will have it's own local copy of an instance variable.