aspose file tools*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 751
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: 18103
    
  39

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: 751
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
 
Similar Threads
Private Static
an object can call static method.
UCertify Questions
Inheritance Confusion
Accessing a static method in a non static way