Reputation: 19
In java, I have two classes in two separate files, and I'm trying to get my print method to work in the second class. The print method is a non-static (it has to be non-static, no choice) this is some of the print code:
public void print() {
System.out.print(re);
if (im < 0) {
System.out.print("something");
}
else if (im > 0) {
System.out.print("something else");
}
System.out.println("");
return;
}
And every time I try to print in the second class, I find that non-static method print() cannot be referenced from a static context. How do I get this to print in the new class?
Upvotes: 0
Views: 5143
Reputation: 351
In almost every java application, I tend to write a default main method to break out of the static one. Here's an example of how I accomplish it. Maybe this will help you when writing future applications.
public class Foo {
public int run (String[] args) {
// your application should start here
return 0; // return higher number if error occurred
}
public static void main (String[] args) {
Foo app = new Foo();
int code = app.run (args);
System.exit (code);
}
}
Upvotes: 0
Reputation: 24780
You create an instance of the class with the non-static method.
MyClass myObject = new MyClass();
myObject.print();
Upvotes: 2