Aarish Ramesh
Aarish Ramesh

Reputation: 7023

Ambiquity in choosing the main class in NEtbeans though a public class is declared

While running this code in netbeans,it asks me to select the main class.. why doesn't it by default choose the public class to be the main class and run?

class Staticclasss2{
    public static void main(String[] args){
        System.out.println("Hello world from staticclasss2");
    }
}
public class Staticclasss{
    public static void main(String[] args){
        System.out.println("hello world from Staticclasss");
    }
}

Upvotes: 2

Views: 76

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 41945

The class containing main() method does not have to be public, just the main() method MUST be public for the JRE to pick it up to start your program.

So in your case there are two classes that contain a public main() method, so netbeans asks you to choose from the two options.

Same is the scenario with Eclipse.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500675

why doesn't it by default choose the public class to be the main class and run?

Simply because the access level of a class is not an aspect which is relevant when picking an entry point class. While main has to be public, the class itself doesn't... and often you wouldn't want it to be. (After all, you're typically not calling this from other code. I'd rather be in a situation where main could be private, but that's another matter.)

Both options are equally valid, so the situation is inherently ambiguous.

Upvotes: 3

Related Questions