By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,468 Members | 1,865 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,468 IT Pros & Developers. It's quick & easy.

Class Instance

P: 2
Hello,
I have been trying to instantiate a class dynamically within a loop. I have this code:
for(int m=1;m<5;m++){
mystring = Integer.toString(m);
String b2 = "myobservation"+mystring;
Observation ob = (Observation)b2;
System.out.println(ob);
}

where Observation is the class I want to instantiate. All I want to do is instantiate the Observation class with the new name "myobservation" i times.
Can you please help me with this?
Thank you!!
Nov 13 '06 #1
Share this Question
Share on Google+
1 Reply


10K+
P: 13,264
Hello,
I have been trying to instantiate a class dynamically within a loop. I have this code:
for(int m=1;m<5;m++){
mystring = Integer.toString(m);
String b2 = "myobservation"+mystring;
Observation ob = (Observation)b2;
System.out.println(ob);
}

where Observation is the class I want to instantiate. All I want to do is instantiate the Observation class with the new name "myobservation" i times.
Can you please help me with this?
Thank you!!
To instantiate an object, you use the object's constructor
eg
Expand|Select|Wrap|Line Numbers
  1.  Observation ob = new Observation(b2);
Now notice that I have passed b2 to the constructor of Observation. This may or may not work depending on whether or not the Observation has a constructor defined that accepts a string.

What you were doing is trying to typecast a String to an object of type Observation. This will only work if String is convertibe to Observation ie if Observation is a subclass of String (which seems unlikely in this case).
Nov 13 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.