| 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
|
|
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...
|
 |
 |
|
|
subject: Why i can access static variable with Class Instance
|
|
|