I have a problem in instantiating an object using a variable. It can be done this way : Student foo = new Student(); but instead of this , I want to be able to store this Student in nother variable like myVar and then instantiate Student like this : foo = new myVar; I know this can be done in C using function pointers but was thinking of a way in java, thanks Vishal.
As I read your post, you want to create objects without hard-coding their type into your program. This is easy to do in Java. If myVar is a String whose value is "Student", then you can write
Now, note that "var" is of type "Object". It can't be of type "Student", of course, since the code doesn't "know" about that class. This limits what you can do with "var" -- but there's more to it than that, of course. This is enough to get you started. Come back and ask more questions once you've fiddled with this. P.S. C doesn't have objects, so no amount of fiddling with function pointers would let you do this! Even in C++, this really isn't something you can do. Java is a "dynamic" language, in which this sort of thing is possible; in C++, it's not.
Thanks for ur reply Ernest but I am getting an error that an exception should be declared here. Here it is how I have tried :- String myVar = "Student"; Object var; var = Class.forName(myVar).newInstance(); Here is the error :- mp3/StudentGroup.java [25:1] unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown var = Class.forName(myVar).newInstance(); ^ mp3/StudentGroup.java [25:1] unreported exception java.lang.InstantiationException; must be caught or declared to be thrown var = Class.forName(myVar).newInstance(); ^ 2 errors Errors compiling StudentGroup.
thanks. At line 2 of my code var is of type Object. Will it be of type Student after line 3 ?
Unlike C++, Java enforces checked-exceptions. This means that if a function declares an exception to be thrown, it must eiher be handled by the calling function or thrown by the calling function. So, the messages state that you have to handle two Exceptions: a ClassNotFound exception (thrown by the Class.forName() method) and an InstantiationException (thrown by the .newInstance() method). You could just declare your method to throw these exceptions (if it were a very generic method), but more likely you will want to handle them therein.
Of course (if you're lazy ) you could just have 1 catch block:
[ July 18, 2003: Message edited by: Joel McNary ]
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.