Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between Instance variable & class variable?

 
jami siva
Ranch Hand
Posts: 66
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i understand guys, thanks
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jami:

Glad I could help .

John.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic