This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why i can access static variable with Class Instance

 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

if i declare a public static variable in a class. why i can access the static variable with class instance variable. all though my ide gives warning. static variable should be accessed in a static way.

 
Henry Wong
author
Marshal
Pie
Posts: 20902
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jigar Naik wrote:Hi,
if i declare a public static variable in a class. why i can access the static variable with class instance variable. all though my ide gives warning. static variable should be accessed in a static way.


Because the compiler can easily figure out what class you are referring to, from the instance.

Henry
 
Himanshu Kansal
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Jigar,

This happens because the object you create using "new" can also access the static variable you created. The compiler just looks in the object's space for the variable "var1" and gives what it finds.

Regards
 
Sona Patel
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hii Jigar...

Static variable is part of the class itself. So we can access it using class instance. Only difference is - there will be only one instance of static variable for one or more instances of the class.

Regards...
 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok.. thanks a lot all of you...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic