When I create a new main.java file in the default package in my Eclipse project, it generates a main
method that looks like:
public static void main(String[] args)
{
}
This immediately raises a warning that says This method has a constructor name
. The suggested fix is to remove the void
:
public static main(String[] args)
{
}
Now rather than a warning, I get an error: Illegal modifier for the constructor in type main; only public, protected & private are permitted
. If I remove the static
, my code now looks like:
public main(String[] args)
{
}
This time, I still get an error, but a different one that says:
Error: Main method not found in class main, please define the main method as:
public static void main(String[] args)
Argggh! But that takes me right back to where I started. How do I define the main method so that I don't get any errors or warnings?
I'm using Eclipse Juno Service Release 2 and JavaSE-1.7. Please note, I'm very new to Java; I come from a C# background. Also, this is probably a duplicate question, but I can't find it.
Don't call your class main
, but Main
.
In general, stick to the Java coding standards: start class names with a capital (Main
instead of main
) and you won't run into these problems.
If you name the file main.java
the class has to be named main
too, which is against standard (classes start with a capital letter) but possible. In a class a method named the same as the class is considered a constructor. So to fix your problem and fit the standard rename your class and the file to Main
with a capital "M"
Change the name of your class from main
to Main
or to something else. Also, following the JavaBean API specification, your classes must be in CamelCase with the first letter in capital.
Not 100% related with question, but you should also do not create classes with the names of Java JDK classes, for example String
:
public class String {
public static void main(String[] args) {
System.out.println("Try to execute this program!");
}
}
This won't only give problems to compiler/JVM but also for future readers (remember that you are a future reader of your own code as well).
Note: to fix the code above, just refer to java.lang.String
class using its full name:
public class String {
public static void main(java.lang.String[] args) {
System.out.println("Try to execute this program!");
}
}
Or even better, change the name of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With