Cait
Cait

Reputation: 61

Running methods from another class in Java

I've been trying out Java with Eclipse and I'm having trouble running methods from another class. I have read other posts about this subject, but I still couldn't get it to work.

Here is my code: (All files are in the same Java project)

(Code from one file called Hello.java)

public class Hello {
    public void printText(){
        System.out.println("Hello World");
    }
}

(Code from another file called TestHello.java)

public class TestHello{
    public void main(){
        Hello hello = new Hello();
        hello.printText();
    }
}

So, in Eclipse, I save all the files, and then press CTRL + F11 to run the file called TestHello.java, and it is supposed to use the method from Hello.java and print Hello World but it doesn't print anything. It gives me an empty console.

Any help is appreciated, thank you very much.

Upvotes: 1

Views: 124

Answers (2)

This here is wrong because the start point of the app is static void main(String[] ars)

public void main(){
        Hello hello = new Hello();
        hello.printText();
    }

it must be

public static void main(String[] args){
        Hello hello = new Hello();
        hello.printText();
    }

Upvotes: 0

f1sh
f1sh

Reputation: 11942

In order to run a java file, you need a main method, but it has to look exactly like this:

public static void main(String[] args){
   //code here
}

your public void main() is not correct.

Upvotes: 7

Related Questions