开发者

Java Main - Calling another method

I have the following code below:

开发者_开发百科public static void main(String args[])
{
start();
}

i get this error: Non-static method start() cannot be referenced from a static context.

How can i go about doing this?


Create an instance of your class and call the start method of that instance. If your class is named Foo then use the following code in your main method:

    Foo f = new Foo();
    f.start();

Alternatively, make method start static, by declaring it as static.


Hope this can help you..

public class testProgarm {

    private static void start() {
        System.out.println("Test");
    }

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

}

However, it is not a good practice to make a method static. You should instantiate a object and call a object's method instead. If your object does't have a state, or you need to implement a helper method, static is the way to go.


One approach would be to create an instance of another class within the main method, for example newClass and call the start() method within it.

newClass class = new newClass();
class.start();


For non-static (& instance) methods, you may need an instance of class to access it.

Try this:

public class TestClass {

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

       TestClass tc = new TestClass();
       tc.start1()
    }

    // Static method
    private static void start() {
        System.out.println("start");
    }

    // Non-static method
    private void start1() {
        System.out.println("start1");
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜