Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP 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: 21362
84
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