Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confusing statics!!!

 
Lakshmi Manikantan
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following piece of code is on Initializers:
----------------------------------------------------
public class Init {
private static String msg(String msg) {
System.out.println(msg);
return msg;
}
static String m=msg("1");
{m=msg("2");} //---(1)
static{m=msg("3");}
public static void main(java.lang.String[] args) {
Object o= new Init();
}
}
-----------------------------------------------------------
when this is compiled u get :
1
3
2
as the output!!!
Fine!!!...but my doubt is how can a static variable be reinitialised when instantiated(at line (1))...static variables belong to a class and not to the instance ,right???
------------------
lakshmi
 
April.Johnson
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct. Static variables do belong to the class. "Variable m is static; this means that there is only one m, no matter how many instances of class Init might exist at any moment" (Complete Java 2 Certification Study Guide 2nd Edition, page 87, bottom of the page. I italized to change the variable and class names to match your question.).
You may be confusing the static modifier with the final modifier.
The static modifier just means that there is one m, even if there are 100 objects of class Init. Any one of those 100 objects are free to change m, they're just all changing the same one, instead of having their own.
Also static allows access of a variable or method without having an instance of the class.
The final modifier means that after being initialized, a variable cannot be reassigned. Often a final variable is initialized when it is declared, as in:
final float pi = 3.14F;
In this case, pi can never be reassigned another value. pi will always be 3.14F. Writing pi = 4.3F will result in a compiler error.
I digress.
April
[This message has been edited by April.Johnson (edited June 19, 2001).]
[This message has been edited by April.Johnson (edited June 19, 2001).]
 
Junilu Lacar
Bartender
Pie
Posts: 7465
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's perfectly legal for instance methods and initializers to access class variables. What is illegal is for static methods and initializers to access instance variables.
It makes sense to allow instances to access class variables since class variables are shared by all instances.
Perhaps you are confusing final with static. final variables cannot be assigned a new value once they have been initialized.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic