| Author |
difference between Instance variable & class variable?
|
jami siva
Ranch Hand
Joined: Oct 16, 2009
Posts: 55
|
|
Hi,
I read a sentance in K & B, Instance variables Cannot be marked static, because then they'd become class variables.
As of now i know the variables declared as static are called class variables,
Here in below i wrote
This code is compiled , what is it mean by instance variable can not be marked static
Thanks
Sivva
|
 |
Jelle Klap
Bartender
Joined: Mar 10, 2008
Posts: 1405
|
|
The variable declared at line 4 is an instance variable. You can certainly declare this variable static, but then it becomes a class variable.
So, the reason you can't declare an instance variable static, is because as soon as you do, it becomes a class variable. There's no such thing as a static instance variable.
|
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
Jami:
An instance variable belongs to an individual class object. So in this class:
The String 'name' is an instance variable. Every object of this class has its own copy of name (which is set when the class is instantiated). The int 'counter' is a static variable, which means that it is shared by all objects of type Example. So, if you create three objects of type Example, counter will end up with a value of 3 (ignoring thread-safety issues).
John.
|
 |
jami siva
Ranch Hand
Joined: Oct 16, 2009
Posts: 55
|
|
|
i understand guys, thanks
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
Jami:
Glad I could help .
John.
|
 |
 |
|
|
subject: difference between Instance variable & class variable?
|
|
|