aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final instance variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "final instance variable" Watch "final instance variable" New topic
Author

final instance variable

Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521


why doesnt the variable gets initalised to 0 when the a object is created? and why is it so that the varibale should be assigned a value before the contrcuotr gets over?


scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown
Martin Sergeant
Greenhorn

Joined: May 20, 2003
Posts: 24
All variables marked final should be initialized. You can initialize them with the default value but you have to do this
explicitly i.e. final int x=0 and not final int x;. With member variables, they do not have to be initialized when they are declared, but must be
given a value in the constructor. If you have multiple constructors or if else blocks you must make sure that the
final variable is given value in all the constructors/blocks (but not necessarily the same value) else you will get a compiler error.

Martin
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Final Variable can be initialized in Constructors (in every Constructors). What do you mean by blocks?

Martin Sergeant says....
or if else blocks you must make sure that the
final variable is given value in all the constructors/blocks


Please Explain. Thanks in Advanced!


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

Abimaran Kugathasan wrote:
or if else blocks you must make sure that the
final variable is given value in all the constructors/blocks


Please Explain. Thanks in Advanced!


Basically, what Martin is saying is... that all possible paths during construction, whether a branch is taken or not taken, must initialize a final variable, and initialize it only once.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: final instance variable