This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Why i can access static variable with Class Instance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why i can access static variable with Class Instance " Watch "Why i can access static variable with Class Instance " New topic
Author

Why i can access static variable with Class Instance

Jigar Naik
Ranch Hand

Joined: Dec 12, 2006
Posts: 755
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.



Jigar Naik


Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Himanshu Kansal
Ranch Hand

Joined: Jul 05, 2009
Posts: 257
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


Experience and talent are independent of age
Sona Patel
Ranch Hand

Joined: Mar 30, 2009
Posts: 75
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

Joined: Dec 12, 2006
Posts: 755
ok.. thanks a lot all of you...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why i can access static variable with Class Instance