Java程序中是否必须使用Main方法? [英] Is the Main method must needed in a Java program?

查看:394
本文介绍了Java程序中是否必须使用Main方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写java程序需要主要方法吗?

Is the main method needed to write a java program?

这是我的代码:

package example;

public class HelloWorld {

    public HelloWorld() {

    }

    public String getHelloWorld() {

        return "Hello From Java!";
    }
}

它在编译时显示错误:

java.lang.NoSuchMethodError: main
Exception in thread "main"


推荐答案

java程序中不需要main方法。正如其他人所指出的那样,Web应用程序不使用main方法。

The main method is not needed in java programs. As others have pointed out, web applications do not use the main method.

在独立应用程序中甚至不需要它。考虑

It is not even needed in standalone applications. Consider

class JavaAppWithoutMain
{
    static
    {
    System . out . println ( "Hello World!" ) ;
    }
}

我编译并运行并获得以下结果:

I compiled it and ran and obtained the following result:

Hello World!
Exception in thread "main" java.lang.NoSuchMethodError: main

对于独立应用程序你必须要

For standalone applications you must either have


  1. 主要方法或

  2. 静态初始值设定项。

主要是首选。

这篇关于Java程序中是否必须使用Main方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆