THL
THL

Reputation: 19

How to get a non-static method to print in a static main in a new class?

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

Answers (2)

cmevoli
cmevoli

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

SJuan76
SJuan76

Reputation: 24780

You create an instance of the class with the non-static method.

 MyClass myObject = new MyClass();
 myObject.print();

Upvotes: 2

Related Questions