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
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply 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: 744
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: 16687
    
  19

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: 744
ok.. thanks a lot all of you...
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Why i can access static variable with Class Instance
 
Similar Threads
Inheritance Confusion
Private Static
an object can call static method.
Accessing a static method in a non static way
UCertify Questions