Java – code in public static void main, or use code to call another method in main?

In the tutorials on the Internet, I often see code fragments in public static void main (String [args]), while my programming course instructor usually writes a method and calls the method in main.

For example, in the tutorial, I will see:

class Person {
    public static void main(String[] args) {
        int age = 20;
        System.out.println(age);
    }
}

My lecturer will write:

class Person {
    void run() {
        int age = 20;
        System.out.println(age);
    }

    public static void main(String[] args) {
        new Person().run();
    }
}

Is there a difference between the two, or is it just a preference?

Solution

From an output point of view, there is no difference because both display the same thing From a technical point of view, the first example is faster than the second

@Adam arold has mentioned technical differences I will emphasize the principle of programming, which is the main difference here

The second example follows a standard coding principle called SOC (separation of concerns) SOC means that each class / method should only have code related to what they should do, because any additional functionality should be handled in a separate class / method The main method is the entry point. The main method is responsible for configuring settings and starting the program, rather than processing any business logic (the business logic here is to print a line) Your instructor follows standard practice:) even simple examples

It sounds like your lecturer is a pretty good programmer:)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>