Calling Methods In Java - Hello World Example [dup

2019-09-13 00:57发布

This question already has an answer here:

I am slowly but surely working my way through java and have gotten a program to work. However, the program I am using has all of the code in the main method and I'd like to use other methods to keep things better organized.

My question is very simple so I will use the simplest of examples. Say I wanted to create a Hello World program like this:

public class HelloWorld {

    public static void main(String[] args) {
        Test();
    }

    public void Test(){
        System.out.println("Hello World!");
    }
}

How do I call Test() correctly in java? The way I have written it creates a compiler error. I am coming from R which would allow something like this.

Thank you.

标签: java methods
3条回答
混吃等死
2楼-- · 2019-09-13 01:48

The method Test() needs to be declared as static, so:

public static void Test(){
        System.out.println("Hello World!");
    }

or you can create a new HelloWorld object and then having it call Test():

public static void main(String[] args){
     HelloWorld foo = new HelloWorld();
     food.Test();
}
查看更多
Ridiculous、
3楼-- · 2019-09-13 01:50

First, your method should be named test (not "Test"). Also, it should be (in this case) static.

public static void main(String[] args) {
    test();
}

public static void test(){
    System.out.println("Hello World!");
}

Or, you could also write it like so,

public static void main(String[] args) {
    new HelloWorld().test(); // Need an instance of HelloWorld to call test on.
}

public void test() { //<-- not a static method.
    System.out.println("Hello World!");
}
查看更多
小情绪 Triste *
4楼-- · 2019-09-13 02:01

See,what you have done with your code is that you have called a non-static method from a static method which is "public static void main(String[] args)" here. Later on,with the time you will come to know that static members are the very first to be called by the compiler and then follows the normal flow of non-static members.

In Java,to call a non-static method,either you need to create a Class object to call a non-static method from the main() method,or you itself declare the non-static method as a static method,which might not be good in every case,but that would simply be called in the main() method as it is!

Correct code(if you want to call non-static methods from a static-method) :-

 public class HelloWorld {

 public static void main(String[] args) {
    new HelloWorld().Test();
 }

 public void Test(){
    System.out.println("Hello World!");
 }
}

Alternative code(if you want to call non-staticmethod from a static-method,make the former static) :-

public class HelloWorld {

 public static void main(String[] args) {
   Test();
 }

 public static void Test(){
    System.out.println("Hello World!");
 }
}
查看更多
登录 后发表回答