Reputation: 27
Why the below snippet code use a non-static to run the program??? It there the advantages of running the program in that style???
public static void main(String[] args) {
Main go = new Main();
go.start();
}
public Main() {
}
public void start() {
//SOME CODE HERE
}
Upvotes: 1
Views: 1289
Reputation: 21778
Classic object-oriented approach encourages encapsulation: everything must be local as much as possible and multiple instances of the class must be possible. Global is bad and ugly.
Object-oriented approach also encourages inheritance, polymorphism and possibility to override methods with well defined functionality. Or, alternatively, composition (compose alternative versions of the complex object from well defined sub-components).
While a single and simple static method looks not much different from a single and simple non-static one, it can only easily make calls to other static methods of this class and can only access static variables simply.
This blocks the advanced architectures that make no difference for the simple "hello world" but worth to consider if you want to grow up a big and complex application out of this stub.
Upvotes: 2
Reputation: 140525
Basically, there are two advantages of having a main()
that simply instantiates an instance of the corresponding class, to then call methods on that object:
it allows you to "re-use" that Main class in a more object oriented way. If another class wants to use Main
, calling a static method to get that going is most often not what you want (it makes unit testing harder for example to use static methods). Therefore, if "re-use" is one of your requirements, then making it possible to instantiate that class, and using it without calling its static main()
can be beneficial.
beyond that, it also makes it a bit easier to unit test the main class as well.
Upvotes: 5