This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Initializers  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, in java can an instance initializer assign a value to a static member? I thought that instance initializers were only for instance members and not for static ones too
thanks
 
Jhonson Fernando
MyExamCloud Software Support
Ranch Hand
Posts: 692
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you can initialize static members inside your constructor.

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you can initialize static members inside your constructor.
thanks but I wasn't talking about constructors but instance initializers :-)
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:
Yes you can initialize static members inside your constructor.
thanks but I wasn't talking about constructors but instance initializers :-)


Static fields can be accessed from constructors, methods, and instance initializers.

Henry
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:Hi guys, in java can an instance initializer assign a value to a static member? I thought that instance initializers were only for instance members and not for static ones too

Let's assume you have a class with 5 constructors without constructor chaining (using this()) and you need to keep track of the number of instances being created.

You can either duplicate incrementing the counter in each constructor, or you could use an instance initializer block to increment this counter. Here's a simple code example (you have to imagine those five constructors yourself )
 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clear, thanks guys!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!