MhdSyrwan
MhdSyrwan

Reputation: 1633

is there any benefit of writing public classes for the main method?

We can write a java program with one non-public class containing a main method -- it'll compile and run just fine. Why do people make the main class public?

Is there any benefit?

Upvotes: 2

Views: 1269

Answers (3)

csarathe
csarathe

Reputation: 430

Benefit you will have only when classes you are using in main method doesn't belong to same package.Public class will have visibility across all the packages.

Upvotes: 0

Ankur Agarwal
Ankur Agarwal

Reputation: 24788

Simply because clients will have access to create objects of your class based on the accessibility you specify for your class. If you look at Java source libraries you will see lot of private (inner classes) classes too. Depends whom do you want to allow access to create objects of your class.

Upvotes: 1

corsiKa
corsiKa

Reputation: 82599

There is no benefit of making the class public for the sake of it having a main method.

That being said, there isn't really much of a reason not to either. Chances are the main class is either going to be very short with few, if any, substantial methods in it, or it's going to be baked into one of the core classes like

class Server {
    public static void main(String[] args) {
        Server s = new Server();
        s.start();
    }
    // rest of Server class here
}

And typically those core classes are something you'd want to be public.

But this isn't about the benefits of having classes be public. This is about the benefits of having a class be public because it has the main method and there are no direct benefits as a result of that.

Upvotes: 2

Related Questions