| Author |
Global constant in a static block
|
Ian Lubelsky
Ranch Hand
Joined: Feb 10, 2010
Posts: 49
|
|
I've been working on the assignment NaturalLanguageMultiply. One of the things I can do is create a global constant if I want and I have a question about the form of a constant in a static block.
I took the example from the exercise, so as not to give anything away from the assignment. Of course it could also be my way of ensuring no unnecessary nitpicking if I goofed it somewhere.
On line 4, I write "static", but I'm not sure why. In my script I've been able to compile it and run it with and without that line. I'm wondering what purpose it serves. I tried looking the answer up on the net, but all I get is more examples of scripts written with the line "script" and how to initialise a block; but none that explains to me why I need to put the word "static" in the code.
Thanks for any info on this.
|
 |
Janeice DelVecchio
Saloon Keeper
Joined: Sep 14, 2009
Posts: 1611
|
|
Hmmm.... I think I have used resources that don't include the second 'static,' and thus have always omitted it.
I wonder if it's style or function.....
|
When you do things right, people won't be sure you've done anything at all.
|
 |
d vasu
Greenhorn
Joined: Sep 12, 2010
Posts: 1
|
|
Ian Lubelsky wrote:
On line 4, I write "static", but I'm not sure why. In my script I've been able to compile it and run it with and without that line. I'm wondering what purpose it serves.
I see that you want to know about the significance of the "static block". The "static block" runs only once i.e; at the time when the class loads. A block without keyword static is called "instance block" and it runs every time an instance is created.
Try this : create a static block and an instance block in the same program and create two or more instances of the same class in the main() method ...... You will see the difference.
A static block runs only at the time of class loading. A static variable has only one copy. A static method can be accessed by using the class name directly.
|
 |
Ian Lubelsky
Ranch Hand
Joined: Feb 10, 2010
Posts: 49
|
|
|
@d vasu. I'm not sure I follow you. I ran the script with and without the word "static" on the 4th line and I encountered no errors at all. That was the only thing I changed in the script before comiling/running it. So I'm still not sure why I need to put that 4th line in.
|
 |
Hauke Ingmar Schmidt
Rancher
Joined: Nov 18, 2008
Posts: 371
|
|
The blocks are initializer; they exist as instance and static initializers: JLS.
You need to look up the difference between static and non-static members and the rules for accessing them (accessing static members from a non-static context).
Do you use an IDE? If yes, you will get a warning in line 6 which should give you a hint. (Edit: You get the warning when you remove the "static" from the initializer.)
|
 |
 |
|
|
subject: Global constant in a static block
|
|
|