Web Hosting Talk







View Full Version : Calling a class in java


cosmic_bird
03-29-2003, 09:44 AM
If I want to access a method of one java class from another java class I go:


ClassName variable = new ClassName();
variable.method();

Thats great, but how can I call a main method of one class from another class i.e. how do I call a class from a class?

jb4mt
03-29-2003, 11:09 AM
Two ways:

The same exact way. Within your object of another class, you open a handle on an object of the class who's method you want to execute, then you call the method.

Other way: if the method you want to call is a CLASS method, or static method, you can call it as follows:

ClassName.methodName();

You don't need an instance of the class to do this, as long as methodName was declared with the static key word.

jb4mt
03-29-2003, 02:30 PM
re-reading your question, how do you call a "main" method from another class? This, as far as I know, you CANNOT do. You need to restructure the first class so that it does not run strictly from the main method. The main method should only be used for testing classes, with a testing framework such as JUnit, or for launching an application, which in turn instantiates all the other classes upon which it depends.

How big is your class? Can you post it or email it and I can give clues as to how to rework things so that your main executable code is not in the main method? One idea is to move it into a method you might want to name something like: execute()

cyansmoker
03-29-2003, 02:59 PM
...which prompts me to ask this question:
Do you have the source code or only the class fileS?

jb4mt
03-30-2003, 08:30 PM
From your email:

Hi, thanks for helping, Below is the class where I want to call the
other class The big code is the class I want to call.

*************************************
package readNews;

public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
while(true) {
//This is where I want to call the class
try {
sleep(36000); //1 minute
} catch (InterruptedException e) {}
}
}
}


Where you want to call the class, insert code from the main method you sent me, starting with:


XMLReader xr = new org.apache.xerces.parsers.SAXParser();
MySAXApp1 handler = new MySAXApp1();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);

URL m_url = new
URL("http://www.newsisfree.com/HPE/xml/feeds/79/79.xml");
InputStream is = m_url.openStream();
xr.parse(new InputSource(is));


You'll probably need to be sure you import the appropriate libraries, for the URL and Input classes. Hope this gets you started. Its a mess of code, and I don't have the Xerces parser installed, so I can't really test it on my box.

ilyash
04-01-2003, 06:40 PM
make your class static... then say classname();