-2

This question already has an answer here:

Any Java code will always have a class which has the same name as that of the file. The whole designed program resides inside this class. However, in C++ we don't have this provision. What is the rationale behind this approach where the whole code resides inside a class? What extra advantage does this provide? Can we create objects of this class and call the main function of this class as many times as we wish?

marked as duplicate by gnat, unholysampler, user22815, GlenH7, durron597 Nov 3 '15 at 23:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

Question 1:

What is the rationale behind this approach where the whole code resides inside a class? What extra advantage does this provide?

I'll link to the same link that gnat provided as a possible duplicate because I think it gives some useful information. The takeaway being that having each public class inhabit its own file allows for faster compilation.

In addition, one of the practical benefits of the Java way of doing things is that we can actually have multiple main functions. In fact, all of your classes could have a main function. You still typically only have one main function in a given project, but I've seen alternative main functions used to:

  • Drive unit/integration/regression tests

  • Create a version of the program with a limited feature set(could be useful when setting up a 'demo'?)

Question 2:

Can we create objects of this class and call the main function of this class as many times as we wish?

Technically, yes you can. Lets say we have:

public class Foo
{
    public static void main(String[] args) {}
}

We can then create objects of type Foo. We can further call main from that object:

Foo obj = new Foo();
obj.main(null);

However, you don't typically do this in Java. main is a static function, meaning you don't need an object in order to call it. It would be just as valid to call Foo.main(null);. In the above obj.main(null);, the obj object is essentially ignored. The Java compiler, by default, should give you a warning against doing this that looks like this:

The static method main(String[]) from the type Foo should be accessed in a static way.

Which again, is just telling you to drop the object and to use the class to call the static method.

However, to answer your question: you can call the static main function as many times as you'd like, just like any other static method. Just remember that you're not calling the object's static main method, you're calling the class's static main method - because objects don't have static methods, classes have static methods.

Not the answer you're looking for? Browse other questions tagged or ask your own question.