类中的方法 vs 主方法下的方法

huangapple go评论73阅读模式
英文:

Method in class vs method under 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");
    }
}

输出:

Method under main method

Method from class

它们做相同的事情,是不是有时候我应该选择一种方式而不是另一种方式呢?

英文:

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?

答案1

得分: 0

我会假设你提到的 "under main method" 是指在主类或文件中创建方法。

在Java中,就像其他任何编程语言一样,你可以只使用主类来创建任何你想要的东西,但这并不是一个好的做法,会创建一个非常大的文件,而且维护起来会非常困难。
你可以在所有的编程语言中使用类来使你的程序更有组织性和易于理解。
(如果我们深入研究复杂的程序,创建类、接口等有很多更多的原因,不仅仅是为了组织代码,但首先掌握基本概念)

什么时候需要创建一个类来保存方法?
这取决于你和你想要组织代码的方式。

如果你在Java方面很新,我建议你稍微了解一下面向对象编程(OOP),这可能会为你提供一些关于何时使用类或不使用类的提示。

英文:

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.

huangapple
  • 本文由 发表于 2020年4月4日 13:50:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61024291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定