Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) 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: 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: 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
Sheriff
Posts: 22607
111
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: 10763
148
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!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!