Calling Methods In Java - Hello World Example [duplicate]

不问归期 提交于 2019-12-13 07:35:13

问题


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.


回答1:


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!");
}



回答2:


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!");
 }
}



回答3:


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();
}


来源:https://stackoverflow.com/questions/23901420/calling-methods-in-java-hello-world-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!