| Author |
Creating array of objects
|
Kaush Kane
Ranch Hand
Joined: May 22, 2006
Posts: 37
|
|
Hi All, I am trying to create an array of objects of a particular class in the following manner
class objectArray { public static void main( String[] args) { String[] args = {"abc", "123"} CreateObjArr[args.length] obj; for (int i=0;i<args.length;i++) { String str = args[i]; //creating each object differently obj[i] = new CreateObjArr(args); obj[i].getString(); } } }
The above approach is giving me error "variable obj might not have been initialized" I know I can create array of objects like this: CreateObjArr[] obj = new CreateObjArr[4]; But as you can see I am creating each object differently. Could you help me out finding a way. Best Regards, Kaustubh Kane
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by Kaush Kane: ...I know I can create array of objects like this: CreateObjArr[] obj = new CreateObjArr[4]; But as you can see I am creating each object differently...
That line will create the array itself (containing null references). It has nothing to do with how the elements themselves are created. Unlike class or instance variables, local variables (like "obj") are not initialized to a default value, so you need to explicitly value them before trying to use them. This would cause the error you are reporting. But I'm really surprised that your compiler got far enough to complain about an uninitialized local variable, because this code has more serious problems. (For example, why are you trying to redefine "args"?)
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Kaush Kane
Ranch Hand
Joined: May 22, 2006
Posts: 37
|
|
thnks a lot. Oh no. My actual code is different and application specific which I cannot share. hence i wrote an equivalent code and in a hurry used "args" Thanks a lot for helping.
|
 |
 |
|
|
subject: Creating array of objects
|
|
|