JAVA: Can an initialization block take parameters from the constructor?
Can one of those...
{ something = somethingElse; } 'initlization blocks' take parameters, or know the parametrs sent in to the constructor?, or are they only useful for doing stuff like { alwaysStartsAtZero = 0; } Thanks. |
I don't understand you question. Do you want to pass parameters to a class constructor?
|
I'm passing arguments to a class constructor, and all of these constructors so far have been just assigning the data members to the parameters...I just read about the intilization blocks, and I thought it would be nice to use those instead (because thats what they're for), but I dont know if the code in the block has 'access' or can 'see' the parameter data passed in to the constructor.
|
Try it out...
but yes I believe so. |
I believe they can't take parameters for at least two reasons:
- there is no way to pass parameters to these blocks - they are executed before the formal constructors which receive the parameters |
Sorry I was thinking of the initialiser list in C++ where you can do that, the initialiser block in Java is to provide default values and thus ensure that the variables are always initialised.
|
Makes sense. I just remembered using the Initilizer lists in c++ and using them for initlization of the data fields, and having my constructors do nothing, as it seemed really cool and badass to do it that way.
Thanks. |
Actually, there is no need to use these blocks to simply have variables initialized, as this can already be done outside any block but the class one.
The interest of these anonymous blocks is that it allows to have pieces of structured programming to be executed before the constructor is called. Another close feature is the anonymous static block, which allows code to be executed once when a class is loaded. |
Thanks. As it turns out Java assigns default values to variables, and in my case I didnt even need the initilization block, as both my referance type and int variable had default variables I was fine with. (null, 0)
|
Quote:
By the way, just as in most lexical languages (all I am familiar with), unnamed blocks can only access activation records and stack frames of blocks surrounding them (and in the case of C, the global space is included in this). Therefore, they can only have access to variables local to themselves and 'outside', lexically. This means no parameters to unnamed blocks :( Besides, if you want to pass parameters to a block, isn't that just a method/function/constructor anyhow, just with a (possible) prior invocation? Look into design. |
All times are GMT -5. The time now is 06:30 AM. |