Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializers

 
Jason Attin
Ranch Hand
Posts: 232
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: 683
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: 232
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
Marshal
Pie
Posts: 22119
88
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: 10662
144
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: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clear, thanks guys!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic