Method in class vs method under main method

Hudson Eden :

So I have already found this question but I'm having a hard time understanding the answers so sorry that this is a repeat question but when should you use a method written in a class vs a method written under the main method. If you're making a method should't you just put it in a class or are there benefits to writing a method under the main method?

public class MyProgram
{
    public static void main(String[] args)
    {
        method();
        classMethod.method2();

    }

    public static void method(){
        System.out.println("Method under main method");
    }
}

public class classMethod{

    public static void method2(){
        System.out.println("Method from class");
    }
}

Output:

Method under main method

Method from class

They do the same thing is there a time I should use one way over the other?

Carlos Estrada :

I'm goin to assume that for under main method you are referring to create the method on the main class or file.

In java like any other language you can make what ever you want using only the main class but that isn't good, is going to create a really big file and is going to be really hard to maintain. You use classes in all language to make your program more organize and easy to understand. (If we dive into really complex program create classes, interface, etc has a lot more reasons that just organize the code, but stick with the basic)

When you need to create a class to hold methods? That depends on you, and how you want to organize your code.

Its you are really new on Java I recommend to read a little bit on OOP, maybe give you some hints on when you have to use a class or not used.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403605&siteId=1