DEV Community

Calin Baenen
Calin Baenen

Posted on

Can the class containing `main` be private?

I realize, that, in some cases, main shall not be private (and sometimes not protected), and in other cases, it may compile.

But, I was wondering if the class containing main can look like this:

private final class Main {
    public static void main(String[] args) { /* ... */ }
}
Enter fullscreen mode Exit fullscreen mode

.

Top comments (12)

Collapse
 
cyberhck profile image
Nishchal Gautam

Yes, you can make it private, but your JRE (runtime) calls YourJar.main() which isn't available and will fail (its like what happens when you try to invoke a private method) I think it should have exact same error message (because main is called on runtime, compiler doesn't complain, because no one is calling that method, yet)

Collapse
 
calinbaenen profile image
Calin Baenen

Ol, wb the class containing main inside it?

Collapse
 
cyberhck profile image
Nishchal Gautam

I'm not sure if I follow,
basically your java vm will simply call your class.main method, and when it finds that it's private or doesn't even exist, then it'll throw up

Thread Thread
 
calinbaenen profile image
Calin Baenen

Ok. Thanks.

 
calinbaenen profile image
Calin Baenen

Weird. Whenever I click on links to this website, it brings me to the website homepage (index.htm), when I right click, and try to use one of the Open in ... options, it brings me to a smartredirect.de URL, specifically; this one.

Collapse
 
linehammer profile image
linehammer

In Java, each application must have the main method. The main method is the entry point of every java program. The java program searches for the main method while running. This error occurred when the main method is not available. The reason that the compiler don't complain about the public is because it doesn't care about the main method. It doesn't take difference for it if a main exists or not. It's the JVM which need a start point public and static to launch your application.

So you should make your main method as public:

public static void main(String[] args)

The JVM is programmed to look for a specific signature for the main method before executing the program. It finds this signature by looking for a specific series of bytes in the bytecode. That signature only results from compiling a method that is - public static void main. If any of the three modifiers (public, static and void) are omitted the bytecode code will look different and the JVM will not be able to find your main method.

net-informations.com/java/basics/m...

Collapse
 
thefern profile image
Fernando B 🚀

Why not just make main private and run it and see what happens.

 
calinbaenen profile image
Calin Baenen

Thank you.

Collapse
 
calinbaenen profile image
Calin Baenen

Thanks for the recommendation you provided, but, for some reason, when I try to open it, it just closes, as if window.close() was invoked(??).