[hotjoe.com] HotJoe Java Help Forums
  [Search] Search   [Recent Topics] Recent Topics   [Hottest Topics] Hottest Topics   [Members]  Member Listing   [Groups] Back to home page 
[Register] Register / 
[Login] Login 
Visit java.com
Please send email if you are having login problems - see the posts below for more info.
Hotmail and Yahoo! users - please see the Hotmail post or the Yahoo! post for information on lost emails.
static keyword  XML
Forum Index » New to Java
Author Message
sunnyindia

Newbie

Joined: 01/03/2009 20:25:26
Messages: 1
Offline

Anybody would u let me understand the usage of static keyword in java.Most probably what's my exact doubts are why could'nt we override a method that is static and why we could'nt declare a constructor as static.anybody could pls help me
[Email]
stdunbar

Newbie
[Avatar]

Joined: 06/22/2005 14:51:37
Messages: 849
Location: Superior, CO, USA
Offline

Static for a class field means that there is one and only one instance of the variable. For example:



Now, if I instantiate any number of ExampleClass classes they will all share the same variable. If one class sets "staticVariable" to 10 then all other instances will see it. This has ramifications in multi-threaded programming.

Static can also be used for one-time initialization. A static block will be run only once for any number of the instantiated classes:



The code in the static block will run only once no matter how many instances of ExampleClass are created.

Another usage of static is for methods. Think of a static method as a "global" method on the class. Unlike "normal" methods you can call a static method without creating an instance of the class. So if you had:



Now any other code could just call:



without having to create a new ExampleClass. Static methods only have access to static variables within the class. Normal member variables are not accessible because those are created on a per-instantiation basis. So:



However, in "normal" methods the opposite is not true. You can access a static variable just fine:



But you will need an instantiated version of ExampleClass to call printHello2:



Does this make a bit more sense now?

Thanks for using the forums at hotjoe.com
[WWW] [Yahoo!] [ICQ]
 
Forum Index » New to Java
Go to:   
Powered by JForum 2.1.9 © JForum Team
This site run by Scott Dunbar of Xigole Systems. © 2005-2011 - Scott Dunbar
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners
hotjoe.com, xigole.com, and Scott Dunbar have no affiliation with Oracle