Forums Register Login

How to access the method using the object

+Pie Number of slices to send: Send
Dear friends...
Can any one tell me what should I do to access the watch() method using the object obj in the following program.

Your suggestion are highly welcomed.

***********************************************************************
public class Manoj
{
String you="YOU";


Manoj()
{
System.out.println("In const");
}
public void watch()
{
System.out.println("In Watch");
}

public static void main(String a[]) throws
InstantiationException,IllegalAccessException
{
try
{
Object obj = Class.forName("Manoj").newInstance();
//obj.watch();
//System.out.println("Your Entered String: "+obj.you );

}
catch(Exception e)
{
System.out.println("Ex: "+e);
}

}
}
*********************************************************************
+Pie Number of slices to send: Send
Hi manoj,

" Object obj = Class.forName("Manoj").newInstance();" Their is a problem with this line i suppose.If we create a instance by new its working instead of the above.

Ganesh Kumar
+Pie Number of slices to send: Send
But Ganesh,
I don't want to use the new operator here, because we can create an object without using new operator too. Run the program, you can see that an object is already created, because the constructor is called in the process. But when i tried to access the method watch() with the help of the object obj, its not working, thats what i want to know and what should i do to access the method.

But I am yet to get any help.
Thank you

+Pie Number of slices to send: Send
Ya manoj what you said is right.Lets wait anyone will help us
+Pie Number of slices to send: Send
Since you know what kind of object "obj" is, you can cast it:



You'll need to catch ClassCastException as well.


An interesting twist would be to use an interface here:


The you can instantiate all kinds of classes, and don't have to know which one it is in particular:
+Pie Number of slices to send: Send
Thanks Ditmer
+Pie Number of slices to send: Send
Thank you Ulf, your suggestion was very helpful. Now I am able to compile and run the program efficiently. Thanks once again.

I have gone to look for myself. If I should return before I get back, keep me here with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 890 times.
Similar Threads
newInstance() doubt
To map backing bean from a selected drop-down value
When to use new and newInstance() and what is the difference bet them.
newInstance of abstract class?
MySQL drivers
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:19:27.