• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does it matter where you initialise global attributes?  RSS feed

 
Alan Smith
Ranch Hand
Posts: 185
Firefox Browser Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

just wondering as the subject bar says....

ie.



or



is there any difference whether you initialise global variables in the constructor or not. The only global variables I usually initialise outside the constructor are static variables.

Thanks,
Alan
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Smith wrote:is there any difference whether you initialise global variables in the constructor or not. The only global variables I usually initialise outside the constructor are static variables.

I hate to say, but I think that your "subject bar" is something thing you haven't explained to us. Perhaps you'd care to elucidate?

But (general tip), global variables, in any language, are a bad idea.

Winston
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What global values? I can see no global values; you have an ordinary instance field. Which you are (correctly, I think) initialising in the constructor. This is what global values look likeThose are safe because they are final primitives. If you use reference types as global constants like that, they ought to be immutable.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Smith wrote:Hi,

just wondering as the subject bar says....

ie.



or



is there any difference whether you initialise global variables in the constructor or not. The only global variables I usually initialise outside the constructor are static variables.

Thanks,
Alan


Java doesn't have global variables. Presumably you mean member variables.

If the variable will get the same value no matter which constructor is called, and it's not something that's passed in as parameter to the c'tor, then it makes no difference.

I prefer to initialize member variables at declaration in these situations, because a) I can see the initialization value in the same place as the variable declaration, b) I know at a glance that the value doesn't depend on the c'tors in any way (assuming the person who wrote the code is competent) and c) I don't have to worry about taking care of it in each c'tor.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!