java main() 方法可以指定为私有的还是受保护的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2941450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can the main( ) method be specified as private or protected?
提问by billu
Can the main()method be specified as private or protected?
该main()方法可以指定为私有还是受保护的?
Will it compile?
它会编译吗?
Will it run?
会跑吗?
采纳答案by Chris Dennett
It will compile, it will not run (tested using Eclipse).
它会编译,但不会运行(使用 Eclipse 测试)。
回答by OscarRyz
is the method main( ) can be specified as private or protected?
方法 main() 可以指定为私有的还是受保护的?
Yes
是的
will it compile ?
它会编译吗?
Yes
是的
will it run ?
它会运行吗?
Yes, but it can not be taken as entry point of your application. It will run if it is invoked from somewhere else.
是的,但它不能作为您的应用程序的入口点。如果从其他地方调用它,它将运行。
Give it a try:
试一试:
$cat PrivateMain.java
package test;
public class PrivateMain {
protected static void main( String [] args ) {
System.out.println( "Hello, I'm proctected and I'm running");
}
}
class PublicMain {
public static void main( String [] args ) {
PrivateMain.main( args );
}
}
$javac -d . PrivateMain.java
$java test.PrivateMain
Main method not public.
$java test.PublicMain
Hello, I'm proctected and I'm running
In this code, the protected method can't be used as entry point of the app, but, it can be invoked from the class PublicMain
在这段代码中,protected 方法不能用作应用程序的入口点,但是可以从类中调用它 PublicMain
Private methods can't be invoked but from the class it self. So you'll need something like:
私有方法不能被调用,只能从它自己的类调用。所以你需要这样的东西:
public static void callMain() {
main( new String[]{} );
}
To call mainif it were private.
main如果是私人的,就打电话。
回答by Karthik
Yes, it will compile. But it wil not run as entry point of the program.
是的,它会编译。但它不会作为程序的入口点运行。
Java looks for the public main method signature. If any of the modifiers is different, then it wil assume it as some other method.
Java 查找公共 main 方法签名。如果任何修饰符不同,那么它将假定它为其他方法。
run and test 4 urself. :)
自己运行和测试 4。:)
回答by Matthew Flaschen
You can have as many classes with whatever main methods as you want. They just can't be an entry point unless they match the signature.
您可以根据需要拥有任意数量的具有任何主要方法的类。除非它们与签名匹配,否则它们不能成为入口点。
回答by Peter
Yes, It will compilebut Not Run. It will give you the following errors
是的,它会编译但 不会运行。它会给你以下错误
Error: Main method not found in class A, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
错误:在 A 类中找不到 Main 方法,请将主要方法定义为:public static void main(String[] args) 或 JavaFX 应用程序类必须扩展 javafx.application.Application
Following are the simple code for testing
以下是简单的测试代码
class A {
private static void main(String arg[])
{
System.out.print(2+3);
}
}

